简体   繁体   中英

C# progress bar doesn't show WinForm

What happens is when I click the button to run my code my win form locks up and my progress bar doesn't run. What am I doing wrong?

foreach (string barcount in idit)
{
    barcountmax++;
}

label2.Text = "Total entries:  " + barcountmax;   
progressBar1.Minimum = 0;
progressBar1.Maximum = barcountmax;

...

foreach (string ids in idit)
{
    string[] splitids = ids.Split('|');
    string fixcommacrap = "";
    barmovement++;
    progressBar1.Value = barmovement;
}

My Winform just locks and freezes, i'm unable to see the progress bar.

My guess is that you're doing all the work in the UI thread. Don't do that.

Use BackgroundWorker to do the work, periodically updating the progress bar appropriately, using ReportProgress to allow the UI change to be made in the UI thread.

If you search for BackgroundWorker tutorials you'll find a whole bunch of them, such as this one . Many will give examples using progress bars, as BackgroundWorker is pretty much designed for that scenario.

By default if you are running a long operation the winform is not going to repaint itself. To fix it consider:

  1. Running your computations on a separate thread, preferably using BackgroudWorker
  2. Repainting it manually every time you change your progress bar.

(1) is strongly recommended.

For that to work, you need to let the form paint when necessary. The correct / preferred way is to use a worker thread (perhaps BackgroundWorker) for the long running tasks, calling back to the UI thread periodically to ask it to update the progress.

There is also DoEvents, but that is (frankly) a hack.

The easiest but not correct way to fix the issue is to use the following inside your loop:

Application.DoEvents();

The more challenging is to use separate thread for calculations and current UI thread for updating the progress bar.

As suggested, use a BackGroundWorker.

In the worker, DO NOT update the ProgressBar directly, do it with BeginInvoke.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM