async/await

最简单纯粹的异步函数看起来像下面这样

public async Task DoSomethingAsync()
{
  await Task.Delay(100);
}

async关键字让await关键字生效,并改变了函数结果的处理方式。async关键字就做了这么多,它没有让这个函数运行在一个线程池的线程上。async关键字仅仅是让await关键字生效,并让函数结果的处理方式发生了一些改变。

异步函数的开始部分和其他函数没什么不同,也就是说,它会一直同步运行,直到它遇到await关键字(或者抛出一个异常)。

await关键字是函数开始变成异步的地方,它像是一个一元操作符:它接受一个参数,一个awaitable(一个awaitable就是一个异步操作)。await会检查awaitable是否已经完成,如果它已经完成,那么函数会继续同步运行,就像一个普通函数那样。

如果await发现awaitable尚未完成,那么它就会以异步方式运行。它让awaitable去运行函数剩余部分直到结束,然后从异步函数中返回。接下来,当awaitable结束之后,它会执行异步函数的剩余部分。

If “await” sees that the awaitable has not completed, then it acts asynchronously. It tells the awaitable to run the remainder of the method when it completes, and then returnsfrom the async method. Later on, when the awaitable completes, it will execute the remainder of the async method. 

posted on 2018-12-05 21:51  sPhinX  阅读(192)  评论(0编辑  收藏  举报

导航