Click here to Skip to main content
15,881,624 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

Extension method to update controls in a MultiThreaded WinForm application.

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
18 Jun 2011CPOL 23.5K   17   2
This extension can be used to update controls in a thread safe manner. This method requires a MethodInvoker delegate as input parameter. It just checks whether the control is on a different thread than the caller.
This is the extension method:

C#
public static void ThreadSafeCall(this Control control, MethodInvoker method)
 {
     if (control.InvokeRequired)
     {
         try
         {
             control.Invoke(method);
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.ToString());
         }
     }
     else
     {
         method.Invoke();
     }
 }


Below is the use of it:
txtOutput.ThreadSafeCall((MethodInvoker)delegate { txtOutput.Text = "Updated"; });

License

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


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralInteresting extension method, especially for simple things l... Pin
Riz Thon20-Jun-11 16:18
Riz Thon20-Jun-11 16:18 
GeneralRe: Thanks Riz! Pin
RakeshMeena20-Jun-11 18:43
RakeshMeena20-Jun-11 18:43 

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.