Reputation: 29
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();
}
}
Upvotes: 1
Views: 4464
Reputation: 457217
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 *implementingthem 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();
}
}
Upvotes: 6