I have become painfully aware of just how often one needs to write the following code pattern in event-driven GUI code, where
private void DoGUISwitch() {
Here's an improved/combined version of Lee's, Oliver's and Stephan's answers.
public delegate void InvokeIfRequiredDelegate(T obj)
where T : ISynchronizeInvoke;
public static void InvokeIfRequired(this T obj, InvokeIfRequiredDelegate action)
where T : ISynchronizeInvoke
{
if (obj.InvokeRequired)
{
obj.Invoke(action, new object[] { obj });
}
else
{
action(obj);
}
}
The template allows for flexible and cast-less code which is much more readable while the dedicated delegate provides efficiency.
progressBar1.InvokeIfRequired(o =>
{
o.Style = ProgressBarStyle.Marquee;
o.MarqueeAnimationSpeed = 40;
});