Click here to Skip to main content
Licence CPOL
First Posted 17 Jan 2010
Views 48,550
Bookmarked 197 times

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

By | 8 Oct 2010 | Article
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<t,>(this T isi, Func<t,> 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<t>(this T isi, Action<t> call) where T : ISynchronizeInvoke
        {
            if (isi.InvokeRequired) isi.BeginInvoke(call, new object[] { isi });
            else
                call(isi);
        }
</t></t></t,></t,>
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  

License

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

About the Author

Michael Demeersseman



Belgium Belgium

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questionadd item to listview in backgroundworker without refreshing the listview Pinmemberakul1236:39 8 Feb '12  
AnswerRe: add item to listview in backgroundworker without refreshing the listview PinmemberJuergen Posny23:59 9 Mar '12  
QuestionContext Pinmemberseeblunt22:51 27 Dec '11  
GeneralMy vote of 5 PinmemberOmar Gamil0:57 1 Nov '11  
QuestionFantastic! Works extremely well! PinmemberTheMattster5:15 18 Aug '11  
Generaldemo prog gives error when form closed [modified] PinmemberJames Maeding8:04 16 Dec '10  
GeneralRe: demo prog gives error when form closed PinmemberMichael Demeersseman7:40 22 Dec '10  
QuestionWhy not use Invoke? PinmemberJKranzl0:01 12 Nov '10  
AnswerRe: Why not use Invoke? Pinmemberjcddcjjcd14:16 29 Nov '10  
AnswerRe: Why not use Invoke? Pinmemberjcddcjjcd14:59 29 Nov '10  
GeneralRe: Why not use Invoke? PinmemberJKranzl23:08 29 Nov '10  
AnswerRe: Why not use Invoke? Pinmemberjcddcjjcd20:11 30 Nov '10  
GeneralMy vote of 10... sorry, 5! PinmemberAnt21005:00 2 Nov '10  
GeneralMy vote of 5 PinmemberSohjSolwin4:09 12 Oct '10  
GeneralMy vote of 5 PinmemberMichael Moreno22:20 10 Oct '10  
GeneralVB Implementation [modified] PinmemberNSane11:11 7 Oct '10  
GeneralRe: VB Implementation [modified] Pinmemberlinhjob10:37 29 Oct '10  
QuestionThank you Sir. Where is your Donate button? Pinmemberfree_p20003:04 2 Oct '10  
GeneralEven better... i think... Pinmemberphilippe dykmans9:08 9 Sep '10  
GeneralRe: Even better... i think... PinmemberMichael Demeersseman21:12 9 Sep '10  
GeneralRe: Even better... i think... PinmemberMichael Demeersseman21:09 7 Oct '10  
GeneralOutstanding PinmemberThomas Hauff16:52 6 Apr '10  
GeneralOne more suggestion Pinmemberphilippe dykmans9:30 15 Feb '10  
GeneralExcellante! Pinmemberstixoffire12:18 30 Jan '10  
GeneralRe: Excellante! Pinmemberpredragzakisevic22:01 31 Jan '10  

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 8 Oct 2010
Article Copyright 2010 by Michael Demeersseman
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid