Async and Await - How is order of execution maintained?

前端 未结 2 1601
迷失自我
迷失自我 2021-02-08 21:13

I am actually reading some topics about the Task Parallel Library and the asynchronous programming with async and await. The book \"C# 5.0 in a Nutshell\" states that when await

2条回答
  •  感情败类
    2021-02-08 22:07

    The call of the 'GetPrimesCountAsync' method will be enqueued and executed on a pooled thread.

    No. await does not initiate any kind of background processing. It waits for existing processing to complete. It is up to GetPrimesCountAsync to do that (e.g. using Task.Run). It's more clear this way:

    var myRunningTask = GetPrimesCountAsync();
    await myRunningTask;
    

    The loop only continues when the awaited task has completed. There is never more than one task outstanding.

    So how does the CLR ensure that the requests will be processed in the order they were made?

    The CLR is not involved.

    I doubt that the compiler simply transforms the code into the above manner, since this would decouple the 'GetPrimesCountAsync' method from the for loop.

    The transform that you shows is basically right but notice that the next loop iteration is not started right away but in the callback. That's what serializes execution.

提交回复
热议问题