Terminating two threads with ProgressBar in C #

0

I'm doing a ProgressBar of file conversions, with each converted file, it is updated to ProgressBar with a percentage of the total files to be converted.

I read in a Tutorial how to do ProgressBar , work with Threads with it and here's my problem:

When I cancel the form of ProgressBar (I have a button for this) form is actually terminated, but Conversion keeps running, (I noticed this because these conversions go to a specific folder that keeps getting new files) .

I need to know how to interrupt the two Threads at the same time:

Code

private void bgwProgresso_DoWork(object sender, DoWorkEventArgs e)
{
    for (int i = 0; i < ListaCandidatos.Count; i++)
    {
        Arquivo arq = new Arquivo();
        arq.Linhas = Importadora.LerArquivo(ListaCandidatos[i]);
        arq.SetNome(arq.Linhas);
        arq.Endereco = ListaCandidatos[i];
        arq.SemanaEntrega = arq.GetSemanaEntrega(ListaCandidatos[i]);
        arq.Validacao = true;
        this.EnderecosConvertidos.Add(conv.ProcessarOC(arq));
        int percent = (int)(((double)(i + 1) / (double)(ListaCandidatos.Count - 1)) * 100);
        this.bgwProgresso.ReportProgress(percent);
        pbProgresso.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(pbProgresso.Width / 2 - 10, pbProgresso.Height / 2 - 7));

    }
    if (bgwProgresso.CancellationPending)
    {
        e.Cancel = true;
        return;
    }
    bgwProgresso.ReportProgress(100);

}

private void bgwProgresso_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    System.Media.SystemSounds.Beep.Play();
    this.Close();
}

private void btnCancelar_Click(object sender, EventArgs e)
{
    if (bgwProgresso.IsBusy)
    {
        bgwProgresso.CancelAsync();
    }
    lblStatus.Text = "Cancelado";
    this.Close();
}

private void bgwProgresso_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    pbProgresso.Value = e.ProgressPercentage;
}

I thought it could be if at the end of the Loop and included it in the code, but it also did not work, and it still crashed an Exception into ProgressChanged

Code

private void bgwProgresso_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < ListaCandidatos.Count; i++)
{
    Arquivo arq = new Arquivo();
    arq.Linhas = Importadora.LerArquivo(ListaCandidatos[i]);
    arq.SetNome(arq.Linhas);
    arq.Endereco = ListaCandidatos[i];
    arq.SemanaEntrega = arq.GetSemanaEntrega(ListaCandidatos[i]);
    arq.Validacao = true;
    this.EnderecosConvertidos.Add(conv.ProcessarOC(arq));
    int percent = (int)(((double)(i + 1) / (double)(ListaCandidatos.Count - 1)) * 100);
    this.bgwProgresso.ReportProgress(percent);
    pbProgresso.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(pbProgresso.Width / 2 - 10, pbProgresso.Height / 2 - 7));
    this.pbProgresso.BeginInvoke(
        new Action(() =>
        {
            if (bgwProgresso.CancellationPending)
            {
                e.Cancel = true;
                return;
            }
        }
        ));
}
bgwProgresso.ReportProgress(100);    
}

private void bgwProgresso_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    System.Media.SystemSounds.Beep.Play();
    this.Close();
}

private void btnCancelar_Click(object sender, EventArgs e)
{
    if (bgwProgresso.IsBusy)
    {
        bgwProgresso.CancelAsync();
    }
    lblStatus.Text = "Cancelado";
    this.Close();
}

private void bgwProgresso_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    pbProgresso.Value = e.ProgressPercentage;
}

This Exception was thrown at me:

Error

  

Invalid thread operation: 'pbProgress' control accessed from a   thread that is not the one in which it was created

Update:

Contrary to what I was suggested, I need to close both Threads, not just the ProgressBar view.

    
asked by anonymous 15.04.2016 / 18:11

1 answer

0

It was necessary to implement some actions regarding the cancellation button, it follows revised and functional code:

    for (int i = 0; i < ListaCandidatos.Count; i++)
        {
            Arquivo arq = new Arquivo();
            arq.Linhas = Importadora.LerArquivo(ListaCandidatos[i]);
            arq.SetNome(arq.Linhas);
            arq.Endereco = ListaCandidatos[i];
            arq.SemanaEntrega = arq.GetSemanaEntrega(ListaCandidatos[i]);
            arq.Validacao = true;
            if (bgwProgresso.CancellationPending)
            {
                e.Cancel = true;
                bgwProgresso.ReportProgress(0);
                return;
            }
            this.EnderecosConvertidos.Add(conv.ProcessarOC(arq));
            lblStatus.BeginInvoke(
                new Action(() =>
            {
                lblStatus.Text = string.Format("Convertendo {0} de {1}...", i, ListaCandidatos.Count);
            }
                ));
            int percent = (int)(((double)(i + 1) / (double)(ListaCandidatos.Count)) * 100);
            this.bgwProgresso.ReportProgress(percent);
        }
        bgwProgresso.ReportProgress(100);
    }

    //o que fazer no fim.
    private void bgwProgresso_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Cancelled)
        {
            System.Media.SystemSounds.Beep.Play();
            this.Close();
        } else if(e.Error != null)
        {
            MessageBox.Show("Erro desconhecido");
            this.Close();
        }
        else
        {
            this.Close();
        }
    }

    private void btnCancelar_Click(object sender, EventArgs e)
    {
        if (bgwProgresso.IsBusy)
        {
            bgwProgresso.CancelAsync();
        }
        lblStatus.Text = "Cancelando...";
    }

    private void bgwProgresso_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        if (e.ProgressPercentage >= 100)
        {
            bgwProgresso.Dispose();
            this.Close();
        }
        else
        {
            pbProgresso.Value = e.ProgressPercentage;
            pbProgresso.CreateGraphics().DrawString(e.ProgressPercentage.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(pbProgresso.Width / 2 - 10, pbProgresso.Height / 2 - 7));
        }
    }
    
19.04.2016 / 15:06