65.9K
CodeProject is changing. Read more.
Home

Extension method to update controls in a MultiThreaded WinForm application.

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (3 votes)

Jun 17, 2011

CPOL
viewsIcon

23950

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"; });