65.9K
CodeProject is changing. Read more.
Home

Updating Your Form from Another Thread without Creating Delegates for Every Type of Update

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.85/5 (85 votes)

Jan 17, 2010

CPOL

1 min read

viewsIcon

290942

downloadIcon

5433

Updating your form from another thread without creating delegates for every type of update

Download SimpleThreadSafeCall.zip - 43.07 KB

Introduction

Threads are nice when you need to do stuff in the background without causing your application to hang. Often you want to show the progress of the load that is being handled. In many occasions, that's a progressbar but in some you want to show in detail what is being done. In the first situation where it is only needed to update a progress bar, a backgroundworker can be used. The background worker sends thread safe events. In that event, you can update your progress bar. In the other situations where you want to show more information of what is being done, you need to call the form from within the other thread. If you do that, you will get an invalid crossthreadcall exception. Many articles that discuss the problem explain how to solve the problem by creating delegates and invoking them.

Example: How to: Make Thread-Safe Calls to Windows Forms Controls

delegate void SetTextCallback(string text);
private void ThreadProcSafe()
{
    // Wait two seconds to simulate some background work
    // being done.
    Thread.Sleep(2000);

    string text = "Written by the background thread.";
    // Check if this method is running on a different thread
    // than the thread that created the control.
    if (this.textBox1.InvokeRequired)
    {
        // It's on a different thread, so use Invoke.
        SetTextCallback d = new SetTextCallback(SetText);
        this.Invoke
            (d, new object[] { text + " (Invoke)" });
    }
    else
    {
        // It's on the same thread, no need for Invoke
        this.textBox1.Text = text + " (No Invoke)";
    }
}
// This method is passed in to the SetTextCallBack delegate
// to set the Text property of textBox1.
private void SetText(string text)
{
    this.textBox1.Text = text;
} 

I probably don't have to mention this is a lot of code for one simple textbox update.

An easy alternative

Finally, I found a quick and elegant solution to update a form from another thread. Thanks to some great feedback in the comments i was able to futher perfect the implementation.  The code is as follows:

lblProcent.SafeInvoke(d => d.Text = "Written by the background thread");
progressBar1.SafeInvoke(d => d.Value = i);

//or call a methode thread safe. That method is executed on the same thread as the form
this.SafeInvoke(d => d.UpdateFormItems("test1", "test2"));
 

A threadSafe getter is also available. The getter knows what the return type is, so casting is not necessary.

string textboxtext=textbox.SafeInvoke(d=>d.textbox.text); 

The function SafeInvoke are extension methods.

        public static TResult SafeInvoke(this T isi, Func call) where T : ISynchronizeInvoke
        {
            if (isi.InvokeRequired) { 
                IAsyncResult result = isi.BeginInvoke(call, new object[] { isi }); 
                object endResult = isi.EndInvoke(result); return (TResult)endResult; 
            }
            else
                return call(isi);
        }

        public static void SafeInvoke(this T isi, Action call) where T : ISynchronizeInvoke
        {
            if (isi.InvokeRequired) isi.BeginInvoke(call, new object[] { isi });
            else
                call(isi);
        }
I hope this helps

History

  • 17/01/2010 Article published
  • 30/01/2010 Sample project added and article updated with the comments of philippe dykmans
  • 8/10/2010 Sample project changed and article updated with the comments of philippe dykmans