You can add this extension method that I regularly use (similar in technique to @JaredPar's answer):
/// <summary>
/// Extension method that allows for automatic anonymous method invocation.
/// </summary>
public static void Invoke(this Control c, MethodInvoker mi)
{
c.Invoke(mi);
return;
}
You can then use on any Control (or derivatives) natively in your code via:
// "this" is any control (commonly the form itself in my apps)
this.Invoke(() => label.Text = "Some Text");
You can also execute multiple methods via anonymous method passing:
this.Invoke
(
() =>
{
// all processed in a single call to the UI thread
label.Text = "Some Text";
progressBar.Value = 5;
}
);
Bear in mind that if your threads are trying to Invoke on a control that is disposed, you'll get an ObjectExposedException. This happens if a thread hasn't yet aborted by the application is shutting down. You can either "eat" the ObjectDisposedException by surrounding your Invoke() call, or you can "eat" the exception in the Invoke() method extension.