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