如何使用异步方式连续更新GUI [英] How to update GUI continuously with async
本文介绍了如何使用异步方式连续更新GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
只需创建一个WPF项目.net 4.6
Just created a WPF project .net 4.6
并将此代码放入
lbl1
是GUI上的标签
但是标签永远不会更新,而while循环仅持续1次
But the label is never updated or the while loop continue only 1 time
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var t = Task.Run(
async () =>
{
await AsyncLoop();
});
}
async Task AsyncLoop()
{
while (true)
{
string result = await LoadNextItem();
lbl1.Content = result;
}
}
private static int ir11 = 0;
async Task<string> LoadNextItem()
{
ir11++;
return "aa " + ir11;
}
推荐答案
请使用Application.Current.Dispatcher.Invoke来访问ui线程
Please user Application.Current.Dispatcher.Invoke to access the ui thread
async Task AsyncLoop()
{
while (true)
{
string result = await LoadNextItem();
Application.Current.Dispatcher.Invoke(new Action(() => { lbl1.Content = result; }));
}
}
这篇关于如何使用异步方式连续更新GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文