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

Nau*_*mar 1 c# user-controls winforms

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

((merge.MyControl)(MyControlInstance)).CLIDisplay = e.WorkItem.CustomerId;
Run Code Online (Sandbox Code Playgroud)

我的控件属性显示结果是

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

            }
        }
Run Code Online (Sandbox Code Playgroud)

但是当我把一个类调到我的c#表单时,我得到了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.
Run Code Online (Sandbox Code Playgroud)

ani*_*ine 8

您将不得不使用调用

this.Invoke((MethodInvoker) delegate
{
   lblResultCLI.Text = value;
});
Run Code Online (Sandbox Code Playgroud)

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

跨线程操作无效:从创建它的线程以外的线程访问控件

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

  • 说实话,这是一个糟糕的答案 - 你没有做任何解释**为什么**OP需要使用Invoke. (2认同)
  • 这是重复的,我为什么要打扰?我发布了一个类似问题的链接,并附有一些很好的解释 (2认同)