Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Extension method to update controls in a MultiThreaded WinForm application.

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

License

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

About the Author

SergeyT2
Software Developer
Russian Federation Russian Federation
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140709.1 | Last Updated 21 Jun 2011
Article Copyright 2011 by SergeyT2
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid