Cross-Thread Manipulation of Windows Forms Controls

System.InvalidOperationException: Cross-thread operation not valid. Control "textBox1" accessed from a thread other than the thread it was created on.

The above exception was encountered while placing a function call with long execution time on a separate thread and having that thread update a TextBox with status updates. The issue arises, because “access to Windows Forms controls isn’t inherently thread-safe.”1

Documentation by Microsoft discusses the following solutions:

  • calling the Control.Invoke() method
  • using a BackgroundWorker component
  • setting Control.CheckforIllegalCrossThreadCalls property to false (unsafe)

Invoke() Method

This approach checks whether the currently running thread is the same thread that created the control. If the threads are different, then Invoke() is called to allow running a delegate in the control’s owner thread. Otherwise, the currently running thread is the owner of the control, and the control’s properties can be manipulated directly. This method is demonstrated by the following code snippet:

if (textBox1.InvokeRequired)
   textBox1.Invoke(
      new MethodInvoker(
         () => {textBox1.Text = "abc";} ) );
else
    textBox1.Text = "abc";

Using BackgroundWorker

BackgroundWorker raises three events: DoWork, ProgressChanged, and RunWorkerCompleted.

A DoWork event handler is where long duration functions are called away from the main thread. It runs in a thread separate from the thread that created the BackgroundWorker instance. Modifying a control’s properties from a DoWork event handler will throw System.InvalidOperationException().

The main thread usually creates user interface controls. It also maintains UI responsiveness typically by creating worker threads for lengthy functions. Because BackgroundWorker is likely created from the thread that creates user interface controls, and ProgressChanged and RunWorkerCompleted event handlers execute in the thread that creates BackgroundWorker, it is safe to modify UI controls from ProgressChanged and RunWorkerCompleted event handlers.

With the BackgroundWorker’s WorkerReportsProgress property set to true, event handlers for the BackgroundWorker’s DoWork event can call ReportProgress() to indirectly modify UI controls. ReportProgress() raises the ProgressChanged event, which causes calling of event handlers in the thread that created the BackgroundWorker.

The ReportProgress() method is overloaded. One version of ReportProgress() accepts an integer, which is typically used to represent a percentage of completion. The second version of ReportProgress() accepts an object as well as a percentage of completion. The version of ReportProgress() that accepts an object can be used by the DoWork event handler to send detailed data useful for updating UI controls.

A ProgressChanged event handler added to the BackgroundWorker by the main thread, can inspect the UserState property of the ProgressChangedEventArgs. This property is set to the object provided in the ReportProgress(int, object) call. To set textBox1.Text in the ongoing example, the DoWork event handler can call ReportProgress(0, “abc”) and the ProgressChanged event handler can cast the UserState property to a string and assign it to textBox1.Text:

private void backgroundWorker_ProgressChanged(
   object sender, ProgressChangedEventArgs e)
{
   string s = e.UserState as string;
   textBox1.Text = s;
}

Setting Control.CheckForIllegalCrossThreadCalls to false

Let’s not.

Using BackgroundWorker or the Invoke() method can be applied for different situations. The Invoke() method may be used by a worker thread to show a Modal dialog or MessageBox that prevents the main application form from receiving input while the dialog or MessageBox are displayed. BackgroundWorker allows lengthy methods to run in worker threads while providing feedback to the main thread. Both methods are acceptable mechanisms for cross-thread manipulation of Windows Forms.

Questions, comments, and responses are welcomed and appreciated.

Leave a Reply