[英]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.通过单击调用RunAsync(int)方法的方法,我有一个带有TextBlock和Button控件的 MainWindow。 It was doing some calculations, so the process took quite a long time and blocked the UI.
它正在做一些计算,所以这个过程花费了相当长的时间并阻塞了 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.
我能够将它移动到异步线程,但我完全坚持如何最好地实现在For循环的每次迭代中从该方法更新接口。 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.
如何最好地实现在 For 循环的每次迭代中从此方法更新接口。 Using the progress bar, for example.
例如,使用进度条。
This is what IProgress<T>
is for.这就是
IProgress<T>
的用途。
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` .附带说明一下,如果您使用
Task.Run
调用方法而不是 * them using
,您会发现您的代码更简洁。
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.