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

5 Comments

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”:

        private void button1_Click(object sender, EventArgs e)
        {
            RunButtonClicked();
        }

        private void RunButtonClicked()
        {
            label1.Text = "Hello World";
        }

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:

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

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:

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

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.

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

See more articles on: C#

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 *