Home › C# › Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on
C# · Apr 5, 2016 · 2 MIN READ

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

This error occurs when trying to perform operations on a windows control when using threading. Here we will go through the error and how to resolve it.

We will create a Windows Forms app in Visual Studio:

First, we will create a working simple solution, without using threads.

Add a label and a button:

Add the code on the clicking of the button to set the label1 to “Hello World”:

[sourcecode language=”CSharp”] private void button1_Click(object sender, EventArgs e)
{
RunButtonClicked();
}

private void RunButtonClicked()
{
label1.Text = "Hello World";
}
[/sourcecode]

Running this, clicking the button changes label1 to “Hello World”:

Now, let’s say we move this code to a thread. Adding using System.Threading:

[sourcecode language=”CSharp”] private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(RunButtonClicked);
t.Start();
}

private void RunButtonClicked()
{
try
{
label1.Text = "Hello World";
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
[/sourcecode]

Running this, we get the cross-thread error:

The reason is, Windows form controls are bound to the thread they are created in to achieve thread safety.

To get around this, we can add code to check for InvokeRequired:

[sourcecode language=”CSharp”] private void RunButtonClicked()
{
try
{
if (button1.InvokeRequired)
{
button1.Invoke(new Action(RunButtonClicked));
return;
}
label1.Text = "Hello World";
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
[/sourcecode]

In adding this, when stepping through our code, it will hit the if statement, then go to assign the label to “Hello World”, without error.

 

Carl de Souza
Keep learning. Keep building.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.

Subscribe on YouTube →
Carl de Souza Enterprise Architect at Microsoft · AI Technology Expert

5 Responses to Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

Leave a Reply

Your email address will not be published. Required fields are marked *

Carl de Souza
KEEP LEARNING. KEEP BUILDING.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.