Real-time progress bar update in wpf

I'm having problems with the progress bar showing real-time updates.

This is my code right now

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

But for some reason, the progress bar appears blank when the function starts, and then nothing until the function finishes work. Can someone explain to me how this can be done? I am new to C # / WPF, so I am not 100% sure how to implement the dispatcher in another thread (as seen on some other posts) to fix this problem.

To clarify, my program has a button that, when clicked, captures a value from a text field and uses the API to extract information and creates labels on it. I want the progress bar to be updated after the completion of each row of data.

Here is what I have right now:

private async void search(object sender, RoutedEventArgs e)
{
    var progress = new Progress<int>(value => progressbar1.Value = value);
    await Task.Run(() =>
    {
        this.Dispatcher.Invoke((Action)(() =>
        {
             some pre-processing before the actual for loop occur
             for (int i = 0; i < numberofRows; i++)
             {
                  label creation + adding
                  ((IProgress<int>)progress).Report(i);
             }
        }));
    });
}

Thank!

+4
source share
3 answers

Managed to make it work. All I had to do, not just do it

progressBar1.value = i;

I just needed

progressbar1.Dispatcher.Invoke(() => progressbar1.Value = i, DispatcherPriority.Background);
+13
source

If you are using .NET 4.5 or later, you can use async / await :

var progress = new Progress<int>(value => progressBar.Value = value);
await Task.Run(() =>
{
    for (int i = 0; i < 100; i++)
    {
        ((IProgress<int>)progress).Report(i);
        Thread.Sleep(100);
    }
});

You need to mark your method with a keyword asyncin order to be able to use await, for example:

private async void Button_Click(object sender, RoutedEventArgs e)
+12

BackgroundWorker, .NET, . , BackGroundWorker, .

BackgroundWorker.ProgressChanged .

// This event handler updates the progress bar. 
private void backgroundWorker1_ProgressChanged(object sender,
    ProgressChangedEventArgs e)
{
    this.progressBar1.Value = e.ProgressPercentage;
}

MSDN .

+2

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


All Articles