Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Extension method to update controls in a MultiThreaded WinForm application.

5.00/5 (1 vote)
21 Jun 2011CPOL 8.1K  
You can use Action instead of MethodInvoker as well. And .Invoke at the method is unnesessary.public static void ThreadSafeCall(this Control control, Action method){ if (control.InvokeRequired) { control.Invoke(method); } else { method(); ...

You can use Action instead of MethodInvoker as well. And ".Invoke" at the method is unnesessary.


C#
public static void ThreadSafeCall(this Control control, Action method)
{
    if (control.InvokeRequired)
    {
        control.Invoke(method);
    }
    else
    {
        method();
    }
}

Here is one more useful extension:


C#
public static T ThreadSafeCall<T>(this Control control, Func<T> method)
{
    if (control.InvokeRequired)
    {
        return (T) control.Invoke(method);
    }
    else
    {
        return method();
    }
}

It can be used to return values from a function:


C#
var text = this.ThreadSafeCall(() => Text);

License

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