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.

Upvotes: 3

Views: 3481

Answers (5)

Dave
Dave

Reputation: 15016

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

Upvotes: 1

Scott Arrington
Scott Arrington

Reputation: 12503

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

Upvotes: 2

Stephen Wrighton
Stephen Wrighton

Reputation: 37819

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.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499950

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.

Upvotes: 15

luvieere
luvieere

Reputation: 37494

See if DoEvents can help you out here.

Upvotes: -3

Related Questions