Progress within a Task

Asked

Viewed 115 times

2

How can I modify the values of an interface control within a separate task from the main thread?

Example:

private void button1_Click(object sender, EventArgs e)
    {
        Task task = new Task(Processar);
        task.Start();
    }

public void Processar()
    {
        try
        {
            int i = 0;                

            this.progressBar1.Maximum = 5000000;

            for (i = 0; i < this.progressBar1.Maximum; i++)
            {
                this.progressBar1.Value = i;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

When running this little snippet of code I get this msg...

Cross-thread Operation not Valid: Control 'progressBar1' accessed from a thread other than the thread it was created on

I tried to use delegate, but it didn’t work out so well.

  • Usa Task.Run(() => ...) instead of new Task() and task.Start().

1 answer

3


Using the method Invoke it is possible to accomplish what you want:

    private void button1_Click(object sender, EventArgs e)
    {
        Task task = new Task(Processar);
        task.Start();
    }

    public void Processar()
    {
        try
        {
            Invoke((MethodInvoker)(() => { progressBar1.Maximum = 5000000; }));

            for (int i = 0; i < progressBar1.Maximum; i++)
            {
                Invoke((MethodInvoker)(() => { progressBar1.Value = i; }));
            }
        }
        catch (Exception ex)
        {
            Invoke((MethodInvoker)(() => { MessageBox.Show(ex.Message); }));                
        }
    }
  • 1

    +1, but I think the last line MessageBox.Show(ex.Message) also need to run in the UI thread.

  • I had forgotten the Messagebox, I edited the code to make it correct.

  • It worked perfectly!!! Thank you very much !!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.