Help needed for 'cross-thread operation error' in C#

后端 未结 6 2016
野的像风
野的像风 2021-01-16 03:34

In the following code MessageReceived is on a different thread to label1 and when trying to access it I will get this error:

6条回答
  •  走了就别回头了
    2021-01-16 04:28

    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;
       }
    }
    

提交回复
热议问题