简体   繁体   中英

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.

另一种方法是使用BackgroundWorker(ThreadPool在这里有点过分但技术上可以使用)并让它报告进度。

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++;
    }
}

看看DoEvents是否可以帮助您。

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