帮助在C#中需要的“跨线程操作错误” [英] Help needed for 'cross-thread operation error' in C#
问题描述
在以下code 的messageReceived
是在不同的线程卷标1
,并试图访问它时,我会得到这个错误:
跨线程操作无效: 控制LABEL1从访问 线程比线程这是其他 上创建。
foo.MessageReceived + =新Agent.MessageReceivedHandler(foo_MessageReceived);
无效foo_MessageReceived(消息消息)
{
label1.Text = message.Body;
}
我该如何解决这个问题?
更多:显然我需要使用代理
和引用
,但我不知道如何,能否请您详细介绍一下?
请永远相信你的主线程(GUI线程)上更新您的图形用户界面。
foo.MessageReceived + =新Agent.MessageReceivedHandler(foo_MessageReceived);
公共委托无效MyDelegate(信息MSG);
无效foo_MessageReceived(消息消息)
{
如果(InvokeRequired)
{
的BeginInvoke(新MyDelegate(foo_MessageReceived),新的对象[] {消息});
}
其他
{
label1.Text = message.Body;
}
}
In the following code MessageReceived
is on a different thread to label1
and when trying to access it I will get this error:
Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.
foo.MessageReceived += new Agent.MessageReceivedHandler(foo_MessageReceived);
void foo_MessageReceived(Message message)
{
label1.Text = message.Body;
}
How can I solve this?
More: apparently I need to use delegate
and invoke
, but I don't know how, can you please explain in more detail?
Make always sure you update your GUI on the main thread (GUI thread).
foo.MessageReceived += new Agent.MessageReceivedHandler(foo_MessageReceived);
public delegate void MyDelegate(Message msg);
void foo_MessageReceived(Message message)
{
if (InvokeRequired)
{
BeginInvoke(new MyDelegate(foo_MessageReceived),new object[]{message});
}
else
{
label1.Text = message.Body;
}
}
这篇关于帮助在C#中需要的“跨线程操作错误”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!