Click here to Skip to main content
15,890,670 members
Articles / Programming Languages / C#

Updating the GUI from Another Thread Made Easy

Rate me:
Please Sign up or sign in to vote.
3.09/5 (19 votes)
19 Feb 2007CPOL1 min read 101K   952   50   26
Ever tried updating a control from a background thread and received an error? Here's an easy and clean way to do it...

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

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

couldn't be easier.

The Delegate

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

This defines the signature of the SetText method.

The Method

C#
//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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Europe Europe
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: Hi guys, if you like this.. Pin
daniel.byrne19-Feb-07 6:22
daniel.byrne19-Feb-07 6:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.