Making a progress bar update in real time in wpf

前端 未结 3 1993
我在风中等你
我在风中等你 2020-12-14 18:13

I\'m having some trouble making the progress bar show the updates in real time.

This is my code right now

for (int i = 0; i < 100; i++)
{
     pr         


        
相关标签:
3条回答
  • 2020-12-14 18:49

    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 async keyword to be able to use await, for example:

    private async void Button_Click(object sender, RoutedEventArgs e)
    
    0 讨论(0)
  • 2020-12-14 18:59

    You should use BackgroundWorker included in .NET, which provides you with methods for reporting the progress of a background thread in an event. The thread which created the BackGroundWorker automatically calls this event.

    The BackgroundWorker.ProgressChanged can be used to report the progress of an asynchronous operation to the user.

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

    Refer to MSDN for more information about using this.

    0 讨论(0)
  • 2020-12-14 19:08

    Managed to make it work. All I needed to do is instead of making it just

    progressBar1.value = i;
    

    I just had to do

    progressbar1.Dispatcher.Invoke(() => progressbar1.Value = i, DispatcherPriority.Background);
    
    0 讨论(0)
提交回复
热议问题