本文介绍了C#中的“跨线程操作错误”需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中 MessageReceived label1 不同的线程,当尝试访问它时,我会得到这个错误:



  foo.MessageReceived + =新代理.MessageReceivedHandler(foo_MessageReceived); 

void foo_MessageReceived(message message)
{
label1.Text = message.Body;
}

我如何解决这个问题? >

更多:显然我需要使用委托 code>,但是我不知道如何更详细地解释?

解决方案

永远确定您在主线程(GUI线程)上更新您的GUI。



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 [] {m​​essage});
}
else
{
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:

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#中的“跨线程操作错误”需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:49