非期待已久的UI线程上运行异步方法? [英] Non-awaited async methods run on the UI thread?

查看:86
本文介绍了非期待已久的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
}

这篇关于非期待已久的UI线程上运行异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆