65.9K
CodeProject is changing. Read more.
Home

Extension method to update controls in a MultiThreaded WinForm application.

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jun 21, 2011

CPOL
viewsIcon

8110

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.

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

Here is one more useful extension:

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:

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