There is nothing wrong with that ... but you can add an extension method to make it a little nicer:
public static void InvokeIfNecessary(this Control control, MethodInvoker action) { if (control.InvokeRequired) { control.Invoke(action); } else { action(); } }
Then you can write:
this.InvokeIfNecessary(() => Label1.Text = "Foobar");
Much neat :)
There is a slight performance drawback from creating a delegate when you don't need it, but it is almost certainly insignificant - focus on writing clean code.
Note that even if you do not want to do this, you can still make variable declaration easier in your existing code:
MethodInvoker updateText = () => Label1.Text = "Foobar";
This is one of the advantages of using a separate variable - you don't need the new MethodInvoker
bit to tell the lambda expression what kind of delegate you want ...
source share