Is there a command to update the interface immediately?

I want to update the progress bar from 1 to 100 with this code.

for (int i = 0; i <= 100; i++) {
    System.Threading.Thread.Sleep(100);
    progressBar1.Value = i;
}

But as a result, the UI freezes until the loop ends.

I know it Dispatchercan help, but I don't want to split the function.

Is there any command to update the interface immediately, for example.

for (int i = 0; i <= 100; i++) {
    System.Threading.Thread.Sleep(100);
    progressBar1.Value = i;
    UpdateUINow();
}

Edit: I am using WPF and I am using Thread.Sleep to simulate a lengthy process.

In fact, I want any team to like it Application.DoEvents. But I can not find this command in WPF.

+3
source share
5 answers

, . - .

- - ( , ) ( BackgroundWorker, , ThreadPool) , .

Application.DoEvents - WinForms, , Dispatcher, , WPF - ? , ( ), .

+15

BackgroundWorker (ThreadPool , ) .

+2

# BackgroundWorker . , , Thread.Sleep() .

EDIT: , ,

+2

(GUI) - . , (- ):

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++;
    }
}
+1
-2
source

Source: https://habr.com/ru/post/1723376/


All Articles