Making a progress bar update in real time in wpf

前端 未结 3 1999
我在风中等你
我在风中等你 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(value => progressBar.Value = value);
    await Task.Run(() =>
    {
        for (int i = 0; i < 100; i++)
        {
            ((IProgress)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)
    

提交回复
热议问题