1

I have this error: Cross-thread operation not valid: "Control 'progressBar1' accessed from a thread other than the thread it was created on." I can't seem to figure out how to fix it.

    private void button1_Click(object sender, EventArgs e)
    {
        this.panel1.Visible = false;
        this.panel2.Visible = true;
        new Thread(ProgressBAR).Start();
    }
    private void ProgressBAR()
    {
        Thread.Sleep(5);
        for (int start = 0; start <= 100; start++)
        {
            this.progressBar1.Value = start;
            Thread.Sleep(5);
        }
    }
Brian
  • 5,069
  • 7
  • 37
  • 47
user2267264
  • 63
  • 1
  • 4

3 Answers3

4

Try this:

private void button1_Click(object sender, EventArgs e)
{
    this.panel1.Visible = false;
    this.panel2.Visible = true;
    new Thread(ProgressBAR).Start();
}

private void ProgressBAR()
{
    Thread.Sleep(5);
    for (int start = 0; start <= 100; start++)
    {
        this.Invoke(new Action(() => this.progressBar1.Value = start));
        Thread.Sleep(5);
    }
}

Because of limitations in the OS, you cannot access a UI element from any thread other than the thread that it was created on. The call to Invoke will synchronously invoke the call to update the ProgressBar's value on the main thread.

Dan
  • 9,717
  • 4
  • 47
  • 65
2

You need to use the progress bar's Invoke method to execute the assignment on the control's primary thread:

this.progressBar1.Invoke((Action) () => this.progressBar1.Value = start, null);

You only have to do this when progressBar1.InvokeRequired is true. Consider using this extension class (shameless self-promotion, sorry about that). Then you can forget whether or not you are on the right thread:

this.progressBar1.AutoInvoke(() => this.ProgressBar1.Value = start);
cdhowie
  • 158,093
  • 24
  • 286
  • 300
-1

You must execute the specified delegate on the thread that owns the control's underlying window handle.

For more information see Control.Invoke

Try this:

private void button1_Click(object sender, EventArgs e)
{
   this.panel1.Visible = false;
   this.panel2.Visible = true;
   new Thread(ProgressBAR).Start();
}

private void ProgressBAR()
{
   Thread.Sleep(5);
   for (int start = 0; start <= 100; start++)
   {
      this.Invoke(new Action(() => this.progressBar1.Value = start));
      Thread.Sleep(5);
   }
}
Brian
  • 5,069
  • 7
  • 37
  • 47
KF2
  • 9,887
  • 8
  • 44
  • 77