我想要一个方法(我们称之为M1)执行一些async
循环中的代码(让我们调用第二个方法M2)。在每次迭代中 - UI 应使用以下结果进行更新M2.
为了等待M2, M1需要是async
. But M1应该在 UI 线程上运行(以避免竞争条件),因此它将在没有await
.
我这样想对吗?M1UI的更新会在UI线程上进行吗?
(Extra: It seems OK to have an async void
in this case. Is this correct?)
是的。 (假设您使用返回 UI 线程的同步上下文 - 即来自 WinForm/WPF 的同步上下文)。
请注意,这也意味着您无法以这种方式安排 CPU 密集型操作,因为它将在 UI 线程上运行。
Using void async
是在 WinForms 中处理事件的相当标准的方法:
void async click_RunManyAsync(...)
{
await M1();
}
void async M1()
{
foreach (...)
{
var result = await M2();
uiElement.Text = result;
}
}
async Task<string> M2()
{
// sync portion runs on UI thread
// don't perform a lot of CPU-intensive work
// off main thread, same synchronization context - so sync part will be on UI thread.
var result = await SomeReallyAsyncMethod(...);
// sync portion runs on UI thread
// don't perform a lot of CPU-intensive work
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)