I know that when manipulating UI controls from any non-UI thread, you must marshal your calls to the UI thread to avoid issues. The general consensus is that you should use
I realize that there's already one answer that's pretty much spot on, but I wanted to also post my take on it (which I also posted here).
Mine is a little different in that it can slightly more safely handle null controls and can return results when necessary. Both of these have come in handy for me when trying to Invoke showing a MessageBox on a parent form that might be null, and returning the DialogResult of showing that MessageBox.
using System;
using System.Windows.Forms;
///
/// Extension methods acting on Control objects.
///
internal static class ControlExtensionMethods
{
///
/// Invokes the given action on the given control's UI thread, if invocation is needed.
///
/// Control on whose UI thread to possibly invoke.
/// Action to be invoked on the given control.
public static void MaybeInvoke(this Control control, Action action)
{
if (control != null && control.InvokeRequired)
{
control.Invoke(action);
}
else
{
action();
}
}
///
/// Maybe Invoke a Func that returns a value.
///
/// Return type of func.
/// Control on which to maybe invoke.
/// Function returning a value, to invoke.
/// The result of the call to func.
public static T MaybeInvoke(this Control control, Func func)
{
if (control != null && control.InvokeRequired)
{
return (T)(control.Invoke(func));
}
else
{
return func();
}
}
}
Usage:
myForm.MaybeInvoke(() => this.Text = "Hello world");
// Sometimes the control might be null, but that's okay.
var dialogResult = this.Parent.MaybeInvoke(() => MessageBox.Show(this, "Yes or no?", "Choice", MessageBoxButtons.YesNo));