Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# WPF Indeterminate progress bar

Tags:

c#

wpf

Please could someone suggest why the following doesn't work? All I want to do is display an indeterminate progress bar which starts when the button is clicked, then after I've done some work I set the indeterminate progress bar to false to stop it.

However when I run the code below the indeterminate progress bar doesn't even start. I tried commenting out the line this.progressBar.IsIndeterminate = false and when I do this the progress bar does start but then doesn't terminate.

private void GenerateCSV_Click(object sender, RoutedEventArgs e)
{
    this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate ()
    {
        this.progressBar.IsIndeterminate = true;

        // do some work
        Thread.Sleep(10 * 1000);

        this.progressBar.IsIndeterminate = false;
    }));
}
like image 244
edb500 Avatar asked Aug 28 '16 23:08

edb500


1 Answers

Your code can't work because the "do some work" is happening on the same Thread on which the UI works. So, if that Thread is busy with the "work", how can it handle the UI animation for the ProgressBar at the same time? You have to put the "work" on another Thread, so the UI Thread is free and can do its job with the ProgressBar (or other UI controls).

1) create a method that does the work and returns a Task, so it can be "awaited" for completion:

private async Task DoWorkAsync()
{
    await Task.Run(() =>
    {
        //do some work HERE
        Thread.Sleep(2000);
    });
}

2) Put the async modifier on the GenerateCSV_Click:

private async void GenerateCSV_Click(object sender, RoutedEventArgs e)

3) throw away all that "Dispatcher" / "Invoke" etc stuffs, and use the DoWorkAsync this way:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    PB.IsIndeterminate = true;

    await DoWorkAsync();

    PB.IsIndeterminate = false;
}

So, what's happening now? When GenerateCSV_Click encounters the first await... it begins to work automatically on another Thread, leaving the UI Thread free to operate and animate the ProgressBar. When the work is finished, the control of the method returns to the UI Thread that sets the IsIndeterminate to false.

Here you can find the MSDN tutorial on async programming: https://msdn.microsoft.com/en-us/library/mt674882.aspx If you Google "C# async await", you'll find dozens of tutorials, examples and explanations ;)

like image 151
Massimiliano Kraus Avatar answered Oct 01 '22 15:10

Massimiliano Kraus