Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practices on BackgroundWorker

I am making my first ever C# GUI. It is using a BackgroundWorker to run a computationally heavy simulation. Periodically, the simulation reports (through the ProgressChanged event) a sizable body of information that needs to be displayed in the GUI.

The GUI is divided into controls and I want each control to know how to 'update itself'.

In my research, I found lots of ways I might be able to do this.

  • I could think of was to have the method bougnd to ProgressChanged call an update method on each part of the GUI.
  • I could Invalidate the GUI and bind each controls update method to the Validating event.
  • I could bind each control's update method to the ProgressChanged event.
  • I could have each control implement the INotifyPropertyChanged interface (but I'm skeptical that this would work)

Of all of these options, which one is best practices for updating the entire GUI upon the ProgressChanged event? (or am I out in left field?)

From comment:

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
  Simulation simulation = new Simulation();
  while(true)
  {
    simulation.RunIteration();
    backgroundWorker.ReportProgress(-1, simulation);
  }
}
like image 957
chessofnerd Avatar asked Mar 04 '26 10:03

chessofnerd


2 Answers

You should not have to do anything special.

Your ProgressChanged handler can 'unpack' the data and set the relevant properties of controls. Invalidation and repainting is automatic and it runs on the GUI thread.

You should only be careful with updating 'too often'. How often is too often depends on the volume of data, the handler should be finished well before the next update. If not, build in some throttling mechanism.

like image 172
Henk Holterman Avatar answered Mar 07 '26 06:03

Henk Holterman


ProgressBar is the method I recommend. If the data you want to send to the GUI is text then you could have a rich textbox or just a regular textbox and pass text to it when the progress bar is changed:

public void SomeThread_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    /* Update progress bar */
    ProgressBar.Value = (e.ProgressPercentage);
    if (e.UserState != null)
    {
        TextBox.Text += (string)e.UserState;
    }
}

For other forms of data you could include an If statement which does X when the progress bar is given a certain value.

But ithout knowing more about what you're specifically trying to do I'm afraid I can't provide any more help than that.

like image 23
GeorgePotter Avatar answered Mar 07 '26 06:03

GeorgePotter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!