不期待的异步方法在UI线程上运行?
我想要一个方法(让我们称之为M1 )在循环中执行一些async
代码(让我们调用第二个方法M2 )。 在每次迭代时 – 应使用M2的结果更新UI。
为了等待M2 , M1需要async
。 但M1应该在UI线程上运行(以避免竞争条件),因此它将在没有await
情况下被调用。
我是否正确地认为,通过这种方式, M1的UI更新将在UI线程上?
( 额外 :在这种情况下,如果有async void
似乎没问题。这是正确的吗?)
是。 (假设您使用返回UI线程的同步上下文 – 即来自WinForm / WPF的一个)。
请注意,这也意味着您无法以这种方式调度CPU密集型操作,因为它将在UI线程上运行。
使用void async
是在WinForms中处理事件的非常标准的方法:
void async click_RunManyAsync(...) { await M1(); } void async M1() { foreach (...) { var result = await M2(); uiElement.Text = result; } } async Task 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 }