为什么在新线程c#中将值设置为标签时会出现错误?

时间:2015-05-27 03:59:51

标签: c# multithreading

我正在编写简单的应用程序来加载csv文件,并在c#代码中启动新线程以使用以下代码加载重csv文件:

Thread workerThread = new Thread(DoWork);
workerThread.Priority = ThreadPriority.Highest;
workerThread.Start();


进入DoWork我尝试运行此代码:

 public void DoWork()
 {
 label1.Text = "ok";
 }


但是当收到标签行时我收到这个错误:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll

Additional information: Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on. 


会发生什么?谢谢。

1 个答案:

答案 0 :(得分:6)

当尝试从非UI线程访问UI控件时,这是多线程应用程序的常见错误。不允许从与创建该控件的线程不同的线程访问UI控件。 我通常使用以下命令将调用从非UI线程转到UI线程:

    private void DoWork()
    {
        if (label1.InvokeRequired)
        {
            // this will be called by the non-UI thread
            label1.Invoke(new Action(DoWork));
        }
        else
        {
            // the actual implementation of the DoWork method, this will be called by the UI thread
            label1.Text = "Ok";
        }
    }