In the following code MessageReceived
is on a different thread to label1
and when trying to access it I will get this error:
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();
}));
}