Click here to Skip to main content
12,079,489 members (66,237 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

16.3K views
16 bookmarked
Posted

Extension method to update controls in a MultiThreaded WinForm application.

, 18 Jun 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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)

Share

About the Author

RakeshMeena
Software Developer (Senior)
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralInteresting extension method, especially for simple things l... Pin
Riz Thon20-Jun-11 17:18
memberRiz Thon20-Jun-11 17:18 
GeneralRe: Thanks Riz! Pin
RakeshMeena20-Jun-11 19:43
memberRakeshMeena20-Jun-11 19: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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160212.1 | Last Updated 18 Jun 2011
Article Copyright 2011 by RakeshMeena
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid