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

Extension method to update controls in a MultiThreaded WinForm application.

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
21 Jun 2011CPOL 7.9K   1  
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)


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

Comments and Discussions

 
-- There are no messages in this forum --