Async - await - thread expected

2019-04-12 05:21发布

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:

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!

1条回答
三岁会撩人
2楼-- · 2019-04-12 05:53

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.

You can read more about this here.

查看更多
登录 后发表回答