c# - C#Windows窗体自定义控件跨线程操作

标签 c# multithreading user-controls invokerequired

我有一个主要的Windows窗体,在该窗体中,我有一些自定义控件,它们代表应用程序中的不同屏幕。我想访问此控件的子控件。有些东西我没到这里...有时我会收到此错误:

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

but sometimes everything works OK. I don't completelly understand why the error...probably something with external device (MEI BillAcceptor) which has an event (inside Form1 class) that does the changes to the control... so let me write a simple code...

//user control
public partial class Screen2 : UserControl
{
    public void changeValue(string txt)
    {
        lblText.Text = txt;
    }
}

并在引发特定事件时从form1调用方法changeValue ...
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        BillAcceptor.SomeBillAcceptorEvent += 
            new SomeBillAcceptorEventHandler(changeText);
    }

    private void changeText(object sender, EventArgs args)
    {
        _screen2.changeValue("some text");
    }
}

因此,最令人讨厌的是,有时一切实际上都可以正常工作。所以我的问题是“我必须在这里使用Invoke吗?”或如何通过对应用程序进行较少更改来解决此问题...

最佳答案

是的,如果有可能从其他线程调用该方法,则需要使用Invoke。

您可以检查this.InvokeRequired(),如果为true,则使用invoke,如果为false,则进行常规调用。

关于c# - C#Windows窗体自定义控件跨线程操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8506846/

相关文章:

c# - 如何强制以父类(super class)形式放置控件?

javascript - 如何在 JavaScript 中清空(重置)输入类型电子邮件后用空格填充(in.value =""不起作用)

c# - 更改 C# 字典中项目的基数

c# 修改 getter/setter 但保留简短形式

c# - 在 Form.Dispose() 方法中安全调用

ruby - 如何在Ruby中按顺序执行线程

java - 下面代码中是通过什么方法将任务提交给Executor框架的?

ASP.NET 2.0 异步用户控件不起作用

c# - 将字符串拆分为等长 block 的正则表达式

c# - Java(我的世界)不是从 C# 开始的