错误:"从其创建的线程以外的线程访问"我使用了背景工作者但仍然没有工作

时间:2015-12-16 15:56:15

标签: c# backgroundworker

我有一个更新GUI上的进度条的类。 我使用了backgroundWorker,都使用了' DoWork'和#RunWorkerCompleted'但两人都给了我同样的错误:

"从"

上创建的线程以外的线程访问

我认为通过使用方法" RunWorkerAsync()"它运行GUI线程上的命令,所以我想我错了。

以下是相关代码(尝试了DoWork和RunWorkerCompleted):

this.backgroundWorker2.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker2_RunWorkerCompleted);




private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                this.progressBar1.PerformStep();
            }
            catch (Exception Ex)
            {
                Program.handleException(Ex, MethodBase.GetCurrentMethod().Name);
            }
        }




     //public access from another class, that's my main problem
     //I don't activate the performStep() by pressing a button but its called by progress...
     //BTW, the while loop isn't efficient it is temporary..
         public void performStep()
                {
                    try
                    {
                        this.backgroundWorker2.RunWorkerAsync();
                        while (this.backgroundWorker2.IsBusy)
                        {
                            Console.WriteLine("worker2 is busy");
                        }
                    }
                    catch (Exception Ex)
                    {
                        Program.handleException(Ex, MethodBase.GetCurrentMethod().Name);
                    }
                }

有谁知道为什么它仍然会出错? (顺便说一句,我试图使用代理,但发现这种方式更方便,并由MSDN推荐,所以我想坚持这种方法..)

非常感谢!!

1 个答案:

答案 0 :(得分:1)

Backgroundworker不会在GUI线程上运行命令。它在一个单独的专用线程上运行它们。

要在UI线程上运行,可以使用控件上的Invoke方法:

private void PerformStep()
{
    if (progressBar1.InvokeRequired)
    {
           progressBar1.Invoke(
             new MethodInvoker(() => progressBar1.PerformStep()));
    }
    else
    {
         progressBar1.PerformStep();
    }

}