异步-等待-预期线程 [英] Async - await - thread expected

查看:48
本文介绍了异步-等待-预期线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  static void Main(string[] args)
    {
        Run1();
        Run2().Wait();
    }

    static async Task DoAsyncWork()
    {
        await Task.Delay(2000);
    }

    static async Task Run2()
    {
        var tid = Thread.CurrentThread.ManagedThreadId;
        await DoAsyncWork();
        Console.WriteLine(tid == Thread.CurrentThread.ManagedThreadId);
    }

    static void Run1()
    {
        var tid = Thread.CurrentThread.ManagedThreadId;
        DoAsyncWork().Wait();
        Console.WriteLine(tid == Thread.CurrentThread.ManagedThreadId);
    }

输出是什么

  1. 有时为True,有时为false.

  1. Sometimes True sometimes false.

错误

错误

有时为True,有时为false.

Sometimes True sometimes false.

我认为3是正确的答案,但是当我一直运行代码时,我得到:

I think 3 is the correct answer, but when i run the code all time i get:

错误

我知道为什么第一个打印结果为True,但是任何人都可以向我解释为什么我始终运行代码时会得到False? (我如何在第二张纸上得到True?)

I know why the first print is True but anyone can explain me why when i run the code allways i get False? (how i can get True in second print?)

谢谢!

推荐答案

控制台应用程序没有同步上下文,因此await无法返回前一个线程.这就是为什么您在Run2中看到不同的线程ID的原因.

Console apps do not have a synchronization context so await is not able to return to the previous thread. This is why you are seeing a different thread id in Run2.

您可以阅读有关此 查看全文

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