ProgressBar within a Task

2

How can I change 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 I run this little bit of code I get this message ...

  

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 did not work.

    
asked by anonymous 29.04.2015 / 04:24

1 answer

3

Using the Invoke method, you can accomplish what you either:

    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); }));                
        }
    }
    
29.04.2015 / 05:10