Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify winforms code cross thread calls

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?

like image 483
Mikhail Sokolov Avatar asked May 21 '26 20:05

Mikhail Sokolov


1 Answers

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);
like image 93
Hamish Smith Avatar answered May 23 '26 10:05

Hamish Smith