Is there any command to update UI immediately?
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 the ThreadPool
) and make it call back to the UI thread to update it.
Application.DoEvents
is a hacky workaround in WinForms, but the fact that you've mentioned a Dispatcher
suggests 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.
Another alternative is to use a BackgroundWorker (a ThreadPool would be a bit overkill here but it technically could be used) and have it report progress.
I would use a C# BackgroundWorker to update your UI. This isn't working like you'd expect it to because the Thread.Sleep() is freezing your UI thread.
EDIT: Tutorial that does a bit more what you want here
Ditto on sleeping in the main (GUI) thread -- avoid it at all costs. Although you don't want to Dispatcher, I'd still recommend trying (something like) this:
public partial class Window1 : Window
{
DispatcherTimer _timer = new DispatcherTimer();
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
progressBar1.Value = 0;
progressBar1.Maximum = 100;
_timer.Interval = TimeSpan.FromMilliseconds( 100);
_timer.Tick += ProgressUpdateThread;
_timer.Start();
}
private void ProgressUpdateThread( object sender, EventArgs e)
{
progressBar1.Value++;
}
}
See if DoEvents can help you out here.
精彩评论