用户控件引发异常“跨线程操作无效”

本文关键字:线程 操作 无效 控件 异常 用户 | 更新日期: 2023-09-27 18:34:02

我有一个用户控件和两个类,我想将我的class1的结果打印到用户控件中。我使用此行发送课程结果

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

显示结果的控件属性是

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

但是当我向我的 c# 表单调用一个类时,我遇到了以下异常

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.

用户控件引发异常“跨线程操作无效”

你将不得不使用 invoke

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

下次一定要使用谷歌...

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

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