C# - How to properly use progress bars (GUI's)

2019-08-09 07:48发布

问题:

Instead of a silent program, or one with a console, I wanted to make a progress bar to track the status of each event I am doing.

Events:

  1. Reading/Parsing files
  2. Reading Excel files
  3. Database queries

ect...

Now after I complete one of these tasks I increment the progress bar to indicate that it has completed and I write to a DataGridTable that the status has changed from 'Calculating...' to 'Done.'.

For simplicity say I have a file compute.cs and form.cs. My form boots up and I press 'execute' running the compute.cs script, which relays its status back to the form by:

compute.cs

form.SetStatus(eventId, eventStatus);

form.cs

delegate void SetMetricStatusDelegate(string metric, string status);

public void SetMetricStatus(string metric, string status) { ... }

And finally, the problem. I run my program, each task takes around three seconds to complete, but the progress bar and table is not updating. After all the events have completed, then the progress bar and table update correctly.

What is the proper way to record progress using a progress bar on a C# form?

回答1:

Your UI paint is pausing while the long running tasks are performed.

You need to spawn a thread separate from the UI to perform the long tasks in.

See: BackgroundWorker Class

Beware that accessing UI controls from a thread that did not create them will throw exceptions. Fortunately, the BackgroundWorker has events that you can subscribe to when the thread is complete.