C# WPF Indeterminate progress bar

前端 未结 1 740
清歌不尽
清歌不尽 2021-01-06 09:59

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

相关标签:
1条回答
  • 2021-01-06 10:40

    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 ;)

    0 讨论(0)
提交回复
热议问题