Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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!

like image 549
maz Avatar asked Dec 29 '25 08:12

maz


1 Answers

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.

like image 59
ibebbs Avatar answered Dec 30 '25 20:12

ibebbs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!