Reputation:
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.
Upvotes: 0
Views: 2301
Reputation: 2891
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.
Upvotes: 1
Reputation: 6368
As suggested, use a BackGroundWorker.
In the worker, DO NOT update the ProgressBar directly, do it with BeginInvoke.
Upvotes: 0
Reputation: 1064324
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.
Upvotes: 1
Reputation: 36689
By default if you are running a long operation the winform is not going to repaint itself. To fix it consider:
(1) is strongly recommended.
Upvotes: 1
Reputation: 1504182
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.
Upvotes: 5