c# - UserControl引发异常“跨线程操作无效”

标签 c# winforms user-controls

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

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


我显示结果的控件属性是

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

            }
        }


但是我在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.

最佳答案

您将必须使用invoke

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


下次请确保您使用Google ...

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

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

关于c# - UserControl引发异常“跨线程操作无效”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10548602/

相关文章:

c# - Windows 窗体 - 如何获取 MDIparent 窗体

c# - 如何从 .Net/C# 调用 Schannel 函数

c# - UInt 抛出 OverflowException

c# - 获取字符串的一部分并在 C# 中组合它们?

c# - 如何防止用户在文本框中输入特殊字符

c# - 安全登录表格和注册表(带序列号)

c# - UWP 应用中的 LoopbackExempt

asp.net - 如何获取 asp :CheckBox out of the ViewState? (__ControlsRequirePostBackKey__)

.net - 创建 C++ 控件并在 C# 中使用它可以获得性能吗?

wpf - ScrollViewer 中的用户控件不会在 WPF 中滚动