简体   繁体   English

异步 - 等待 - 线程预期

[英]Async - await - thread expected

i Have the following code: 我有以下代码:

  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);
    }

What will be the output: 什么是输出:

  1. Sometimes True sometimes false. 有时真有时是假的。

    True 真正

  2. False

    False

  3. True 真正

    Sometimes True sometimes false. 有时真有时是假的。

  4. True 真正

    True 真正

I think 3 is the correct answer, but when i run the code all time i get: 我认为3是正确答案,但是当我运行代码时,我得到:

True 真正

False

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?) (我如何在第二次印刷中获得真实?)

Thank! 谢谢!

Console apps do not have a synchronization context so await is not able to return to the previous thread. 控制台应用程序没有同步上下文,因此await无法返回到上一个线程。 This is why you are seeing a different thread id in Run2 . 这就是您在Run2中看到不同线程ID的原因。

You can read more about this here . 你可以在这里阅读更多相关信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM