非期待已久的UI线程上运行异步方法?
我想有一个方法(我们称之为 M1 )执行一些异步
code在一个循环中(我们称之为第二方法 M2 )。在每次迭代 - 用户界面应与结果被更新的 M2
I want to have a method (Let's call it M1) execute some async
code in a loop (Let's call that second method M2). On every iteration - the UI should be updated with the result of M2.
为了等待 M2 M1 必须异步
。但 M1 应在UI线程上运行(以避免竞态条件),因此它会不会被称为等待
。
In order to await M2, M1 needs to be async
. But M1 should run on the UI thread (to avoid race conditions) and therefore it will be called without an await
.
我在想,以这种方式正确,用户界面的 M1 的更新将在UI线程?
Am I correct in thinking that in this way, M1's updating of the UI will be on the UI thread?
(额外:?看来确定有一个异步在这种情况下无效
这是正确的)
(Extra: It seems OK to have an async void
in this case. Is this correct?)
是的。 (假设你使用返回到UI线程同步上下文 - 即一个来自的WinForm / WPF)。
Yes. (assuming you use Synchronization Context that returns to UI thread - i.e. one from WinForm/WPF).
请注意,这也意味着你不能安排CPU密集型操作,因为它会在UI线程上运行的方式。
Note that it also means you can't schedule CPU-intensive operations that way as it will run on UI thread.
使用无效异步
是在WinForms的处理事件非常标准的方法:
Using void async
is quite standard method of handling events in 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
}