简体   繁体   中英

Updating UI from the async method

I have a MainWindow with a TextBlock and a Button controls on it, by clicking on which the RunAsync(int) method is called. It was doing some calculations, so the process took quite a long time and blocked the UI. I was able to move it to an asynchronous thread, but I am completely stuck on how best to implement updating the interface from this method every iteration of the For loop. Using the progress bar, for example.

At the moment i have the following code:

public partial class MainWindow : Window
{
    public MainWindow() => InitializeComponent();

    private async Task<List<int>> RunAsync(int par)
    {
        return await Task.Run(() =>
        {
            List<int> list = new List<int>();
            for (int i = 0; i < par;  i++)
            {
                // some code, that takes quite a long time
                Thread.Sleep(500); 
                list.Add(i);
            }
            return list;
        });
    }
    
    private async void StartBtn_Click(object sender, RoutedEventArgs e)
    {
        int count = (await RunAsync(5)).Count;
        label.Text = count.ToString();
    }
}

how best to implement updating the interface from this method every iteration of the For loop. Using the progress bar, for example.

This is what IProgress<T> is for.

On a side note, you'll find your code is cleaner if you call methods using Task.Run instead of *implementing them using Task.Run` .

public partial class MainWindow : Window
{
  private List<int> Run(int par, IProgress<int> progress)
  {
    List<int> list = new List<int>();
    for (int i = 0; i < par;  i++)
    {
      // some code, that takes quite a long time
      Thread.Sleep(500); 
      list.Add(i);
      progress?.Report(i);
    }
    return list;
  }
    
  private async void StartBtn_Click(object sender, RoutedEventArgs e)
  {
    var progress = new Progress<int>(report => /* Do something with report */);
    var list = await Task.Run(() => Run(5, progress));
    label.Text = list.Count.ToString();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM