How Async and Await works

前端 未结 4 1911
情话喂你
情话喂你 2020-11-28 11:28

I am trying to understand how Async and Await works. How control travel in the program. Here is the code which I was trying to understand.

public async Task          


        
4条回答
  •  猫巷女王i
    2020-11-28 11:48

    Behind the scenes C# compiler actually converts your code into a state machine. It generates a lot more code so that behind the scenes every time a await task or async action is completed, it'll continue execution from where it left off. In terms of your question, every time the async action has finished, the async method will be called back on the calling thread when you originally started the call to the async method. Eg it'll execute your code on the thread that you started on. So the async action will be run on a Task thread, then the result will be returned back on the thread you method was originally called on and keep executing.

    Await will get the value from the Task or async action and "unbox" it from the task when the execution is returned. In this case it will automatically put it into the int value, so no need to store the Task.

    Your code has the problem where it await's on the LongRunningTask() you'd most likely just want to return the long task method without the async, then have your MyMethod perform the await.

    int value = await LongWaitingTask()
    

    Async Await and the Generated StateMachine

    It's a requirement of async methods that you return a Task or void.

    It's possible to change it so when you return back from executing the async task it will execute the remaining code on the thread the async task was performed on using the Task.ConfigureAwait method.

提交回复
热议问题