Explain async await again

前端 未结 4 2029
南方客
南方客 2020-12-06 15:48

This is my event handler code:

protected async void TestrunSaveExecute()
{
    bool saveResult = await SaveTestRunAsync();
}

In order to ke

4条回答
  •  盖世英雄少女心
    2020-12-06 16:22

    Await does not create a thread or a task, it "simply" calls the awaited function (which is not supposed to block, otherwise the caller will be blocked as this is still synchronous), asks the compiler to generate a continuation for the task returned by the awaited function, containing the "rest" of the code after the await, and returns a new task to the caller (if the awaiting function returns a task). That task will be signalled as complete when the continuation completes.

    The framework makes sure the continuation will run on the UI thread (if the application has one), which is a must if you want to be able to access UI elements from the asynchonous functions.

    So an asynchronous function should not contain a blocking call. Blocking calls should be "wrapped" in a task using Task.Run()

提交回复
热议问题