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

后端 未结 6 2020
野的像风
野的像风 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:27

    You need to use Control.Invoke (or Control.BeginInvoke). First, create a new Windows Forms application and add a label and a button. Double click on the button in Visual Studio to edit it's Click event and add the following code:

        private void button1_Click(object sender, EventArgs e)
        {
            new System.Threading.Thread(new System.Threading.ThreadStart(Run)).Start();
        }
    
        void Run()
        {
            label1.Invoke(new Action(delegate()
            {
                label1.Text = System.Threading.Thread.CurrentThread.Name + " " + System.DateTime.Now.ToString();
            }));
        }
    

提交回复
热议问题