UserControl抛出异常“跨线程操作无效”

时间:2012-05-11 09:12:13

标签: c# winforms user-controls

我有一个usercontrol和两个类,我想将class1的结果打印到usercontrol中。我正在使用此行从类发送结果

((merge.MyControl)(MyControlInstance)).CLIDisplay = e.WorkItem.CustomerId;

我的控件属性显示结果是

public string CLIDisplay
        {
            get { return lblResultCLI.Text; }
            set
            {
                    lblResultCLI.Text = value;

            }
        }

但是当我把一个类调到我的c#form

时,我得到了Exception
An exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll but was not handled in user code

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

1 个答案:

答案 0 :(得分:8)

您必须使用调用

this.Invoke((MethodInvoker) delegate
{
   lblResultCLI.Text = value;
});

下次确保您使用谷歌...

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

发生此错误是因为lblResultCLI是在另一个线程上创建的,而不是您运行代码的线程,这就是为什么您必须使用Invoke,以便访问lblResultCLI控件的代码在同一个线程上执行创建于。