1

我有这个错误:跨线程操作无效:“控制'progressBar1'从创建它的线程以外的线程访问。” 我似乎无法弄清楚如何解决它。

    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);
        }
    }
4

3 回答 3

3

试试这个:

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);
    }
}

由于操作系统的限制,您不能从创建它的线程以外的任何线程访问 UI 元素。调用Invoke将同步调用调用以更新ProgressBar主线程上的值。

于 2013-04-10T17:50:23.243 回答
2

您需要使用进度条的Invoke方法在控件的主线程上执行赋值:

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);
于 2013-04-10T17:51:21.273 回答
-1

您必须在拥有控件的基础窗口句柄的线程上执行指定的委托。

有关详细信息,请参阅 Control.Invoke

试试这个:

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);
   }
}
于 2013-04-10T17:50:42.530 回答