gpt4 book ai didi

wpf - 在处理时更新 WPF UI - 异步等待的最佳使用

转载 作者:行者123 更新时间:2023-12-04 12:46:26 25 4
gpt4 key购买 nike

这是我尝试过的 - 就看到 UI 刷新而言,它有效,但我认为这不是异步/等待的最佳用途。我该如何改进?

private async void btnQuickTest_Click(object sender, RoutedEventArgs e)
{
XmlReader reader;
int rowCount = 0;
using (reader = XmlReader.Create("someXmlFile.xml"))
{
while (reader.Read())
{
rowCount++;

DoSomeProcessingOnTheUIThread(reader);

//only update UI every 100 loops
if (rowCount > 0 && rowCount % 100 == 0)
{
//yay! release the UI thread
await Task.Run(() =>
{
Application.Current.Dispatcher.Invoke(
() =>
{
txtRowCount.Text = string.Format("{0}", rowCount);
});
});
}

} //end-while
}//end-using
}

什么是更好的方法?

更新:
我已经根据 Clemens 的回答避免了 Dispatcher.Invoke,方法是将处理发送到后台任务,并直接在 UI 上更新进度。
我的代码现在看起来像。
private async void btnQuickTest_Click(object sender, RoutedEventArgs e)
{
XmlReader reader;
int rowCount = 0;
using (reader = XmlReader.Create("someXmlFile.xml"))
{
while (reader.Read())
{
rowCount++;

await DoSomeProcessing(reader);

//only update UI every 100 loops
if (rowCount % 100 == 0)
{
txtRowCount.Text = string.Format("{0}", rowCount);
}

} //end-while
}//end-using
MessageBox.Show("I am done!");
}

private Task DoSomeProcessing(XmlReader reader)
{
Task t =Task.Run(() =>
{
//Do my processing here.
});
return t;
}

更新#2:
反射(reflection)一下,为什么我要在每个循环上创建一个新任务?
在一项后台任务中运行整个循环可能会更好。并定期提出回调以显示进度;请参阅下面我的另一个答案。

最佳答案

立即调用 Dispatcher.Invoke 的任务毫无意义,因为除了调度 Dispatcher 操作的一小段代码之外,实际上没有任何东西在后台线程上运行。

最好直接设置Text属性,使用XmlReader.ReadAsync :

private async void btnQuickTest_Click(object sender, RoutedEventArgs e)
{
using (var reader = XmlReader.Create("someXmlFile.xml"))
{
int rowCount = 0;

while (await reader.ReadAsync())
{
rowCount++;

await Task.Run(() =>
{
DoSomeWork(reader);
});

if (rowCount > 0 && rowCount % 100 == 0)
{
txtRowCount.Text = string.Format("{0}", rowCount);
}
}
}
}

您也可以考虑制作您的 DoSomeWork async 并直接这样调用它:
await DoSomeWork(reader);

关于wpf - 在处理时更新 WPF UI - 异步等待的最佳使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46231202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com