Click here to Skip to main content
12,449,919 members (45,805 online)
Click here to Skip to main content
Add your own
alternative version

Stats

154.4K views
4K downloads
236 bookmarked
Posted

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

, 8 Oct 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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>
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)

Share

About the Author

No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionBeautiful work. Pin
auralbliss13-Feb-15 4:27
memberauralbliss13-Feb-15 4:27 
QuestionHow do you stop the Thread Pin
Member 1087460526-Aug-14 19:18
memberMember 1087460526-Aug-14 19:18 
QuestionHow to safe call Form from another Thread? Pin
S.Reda10-Nov-13 22:34
memberS.Reda10-Nov-13 22:34 
QuestionWork well, but i'm having issue with some objects Pin
cdebel9-Aug-13 11:58
membercdebel9-Aug-13 11:58 
GeneralMy vote of 5 Pin
MarkBoreham28-Jul-13 7:56
memberMarkBoreham28-Jul-13 7:56 
QuestionNice , need a version for c++/cli Pin
kaand28-Nov-12 5:39
memberkaand28-Nov-12 5:39 
GeneralMy vote of 5 Pin
Mike Barthold23-Oct-12 1:35
memberMike Barthold23-Oct-12 1:35 
Questionadd item to listview in backgroundworker without refreshing the listview Pin
akul1238-Feb-12 6:39
memberakul1238-Feb-12 6:39 
AnswerRe: add item to listview in backgroundworker without refreshing the listview Pin
Juergen Posny9-Mar-12 23:59
memberJuergen Posny9-Mar-12 23:59 
AnswerRe: add item to listview in backgroundworker without refreshing the listview Pin
Henry Minute5-Aug-12 12:10
memberHenry Minute5-Aug-12 12:10 
QuestionContext Pin
seeblunt27-Dec-11 22:51
memberseeblunt27-Dec-11 22:51 
GeneralMy vote of 5 Pin
Omar Gamil1-Nov-11 0:57
memberOmar Gamil1-Nov-11 0:57 
QuestionFantastic! Works extremely well! Pin
TheMattster18-Aug-11 5:15
memberTheMattster18-Aug-11 5:15 
Generaldemo prog gives error when form closed [modified] Pin
James Maeding16-Dec-10 8:04
memberJames Maeding16-Dec-10 8:04 
GeneralRe: demo prog gives error when form closed Pin
Michael Demeersseman22-Dec-10 7:40
memberMichael Demeersseman22-Dec-10 7:40 
QuestionWhy not use Invoke? Pin
JKranzl12-Nov-10 0:01
memberJKranzl12-Nov-10 0:01 
AnswerRe: Why not use Invoke? Pin
jcddcjjcd29-Nov-10 14:16
memberjcddcjjcd29-Nov-10 14:16 
AnswerRe: Why not use Invoke? Pin
jcddcjjcd29-Nov-10 14:59
memberjcddcjjcd29-Nov-10 14:59 
GeneralRe: Why not use Invoke? Pin
JKranzl29-Nov-10 23:08
memberJKranzl29-Nov-10 23:08 
AnswerRe: Why not use Invoke? Pin
jcddcjjcd30-Nov-10 20:11
memberjcddcjjcd30-Nov-10 20:11 
GeneralMy vote of 10... sorry, 5! Pin
Ant21002-Nov-10 5:00
memberAnt21002-Nov-10 5:00 
GeneralMy vote of 5 Pin
SohjSolwin12-Oct-10 4:09
memberSohjSolwin12-Oct-10 4:09 
GeneralMy vote of 5 Pin
Michael Moreno10-Oct-10 22:20
memberMichael Moreno10-Oct-10 22:20 
GeneralVB Implementation [modified] Pin
NSane7-Oct-10 11:11
memberNSane7-Oct-10 11:11 
GeneralRe: VB Implementation [modified] Pin
linhjob29-Oct-10 10:37
memberlinhjob29-Oct-10 10:37 

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.

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