Monthly Archives: February 2007

Updating the GUI from another thread made easy

Introduction

I’ve found out to my absolute horror that even simple operations done in a background thread that need to update the interface are required to force those interface calls back into the same thread as the interface was generated in…

With a bit of research, I found out that this was done with the Invoke method. Initially, I created what felt like hundreds of delegates/functions to handle each control’s update, but now, although this solution I have posted could be better, it is a decent timesaver at least for me, so hopefully it will help someone else…

Basically, what we have below is a static class (ThreadSafe.cs) that has some delegates such as SetText(Control, string) that lets you set the text of any control with some text. The following example is rather basic, but there are numerous others in ThreadSafe.cs such as adding items to listviews, changing checkbox check states etc. Give it a look.

Here is a basic example for changing the Text property of a control.

Usage

ThreadSafe.SetText(this.whateverControl, "text to change");

couldn’t be easier.

The Delegate

public delegate void SetTextDelegate(System.Windows.Forms.Control ctrl, string text);

This defines the signature of the SetText method.

The Method

//generic system.windows.forms.control
 
public static void SetText(System.Windows.Forms.Control ctrl, string text)
{
 
    if (ctrl.InvokeRequired)
    {
        object[] params_list = new object[] { ctrl, text };
        ctrl.Invoke(new SetTextDelegate(SetText), params_list);
    }
    else
    {
        ctrl.Text = text;
    }
}

There are also classes and inherited classes for other controls, listviews, buttons, comboboxes etc., that should save you time writing your thread-safe GUI code. Hope this helps someone. If it does or for help, please leave a comment!

Download Helper Class

ThreadSafe helper