我有一个主要的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/