What is considered good programming practice in multi-threaded winform applications with delegate usage?
A good example is here.
this.BeginInvoke( (Action) (()=> { pictureBox1.Image = Image.FromFile("example.png"); }));
You definitely don't need a separate delegate for each. You can use Action
delegates and lambda expressions to simplify it, like this:
private void SomeOtherMethod(){ Action action = () => pictureBox1.Image = Image.FromFile("example.png"); if (pictureBox1.InvokeRequired) { Invoke(action); } else { action(); }}
Or you can separate out the if
statement and InvokeRequired
check and generalize it even more, like this:
public static void InvokeIfRequired(Control control, Action action){ if (control.InvokeRequired) { control.Invoke(action); } else { action(); }}private void SomeOtherMethod(){ InvokeIfRequired(() => pictureBox1.Image = Image.FromFile("example.png");}
I would use the MethodInvoker
type in conjunction with an anonymous method or lambda expression. I would also build the invocation logic into the method itself, rather than using a separate thread-safe method:
void SomeMethod(/* with whatever args */) { if (InvokeRequired) Invoke(new MethodInvoker(() => SomeMethod(/* args used to call method */))); else // the method body itself}