I want to update a progress bar from running 1 to 100 with this code.
for (int i = 0; i <= 100; i++) {
System.Threading.Thread.Sleep(100);
progressBar1.Value = i;
}
But the result is, the UI freeze until looping finish.
I know Dispatcher can help, but I don’t want to split function.
Is there any command to update UI immediately like..
for (int i = 0; i <= 100; i++) {
System.Threading.Thread.Sleep(100);
progressBar1.Value = i;
UpdateUINow();
}
Edit: I’m using WPF, and I use Thread.Sleep to simulate long running process.
In fact, I want any command liked Application.DoEvents. But I cannot find this command in WPF.
Please don’t sleep in the UI thread. It will freeze your UI – it’s a bad thing to do.
Either have a timer of some kind (use the right kind of timer and you should be able to get it to fire in your UI thread) or use a separate thread (either via
BackgroundWorker, a new separate thread, or theThreadPool) and make it call back to the UI thread to update it.Application.DoEventsis a hacky workaround in WinForms, but the fact that you’ve mentioned aDispatchersuggests you’re using WPF – is that the case? The kind of timer you should use (if you want to use that solution) will depend on the UI framework you’re using.