I'm developing a cross-thread application which have some methods within Invoke:
if (this.InvokeRequired)
{
this.Invoke((Action)(() =>
{
pbTotalProgress.Value = progress;
labe1.Text="SomeText";
}));
}
else
{
pbTotalProgress.Value = progress;
labe1.Text="SomeText";
}
How can I write the code below a bit shorter?
You should, at the least, only define the action once (don't have the code again in the else branch, just run the action there without the invoke.
You could also write an extension method for control that runs an Action as an invoke if required or just runs it. That would get rid of the complexity from your event handler and you will end up using the same pattern for many events in your application.
static class ControlExtensions
{
public static void InvokeOrExecute(this Control control, Action action)
{
if (control.InvokeRequired)
{
control.Invoke(action);
}
else
{
action();
}
}
}
Then in each event that could be cross thread:
Action setProgress = delegate()
{
pbTotalProgress.Value = progress;
labe1.Text = "SomeText";
};
this.InvokeOrExecute(setProgress);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With