Async and Await
http://blog.stephencleary.com/2012/02/async-and-await.html
Most people have already heard about the new “async” and “await” functionality coming in Visual Studio 11. This is Yet Another Introductory Post.
First, the punchline: Async will fundamentally change the way most code is written.
Yup, I believe async/await will have a bigger impact than LINQ. Understanding async will be a basic necessity just a few short years from now.
Introducing the Keywords
Let’s dive right in. I’ll use some concepts that I’ll expound on later on - just hold on for this first part.
Asynchronous methods look something like this:
public async Task DoSomethingAsync()
{
// In the Real World, we would actually do something...
// For this example, we're just going to (asynchronously) wait 100ms.
await Task.Delay(100);
}
The “async” keyword enables the “await” keyword in that method and changes how method results are handled. That’s all the async keyword does! It does not run this method on a thread pool thread, or do any other kind of magic. The async keyword only enables the await keyword (and manages the method results).
The beginning of an async method is executed just like any other method. That is, it runs synchronously until it hits an “await” (or throws an exception).
The “await” keyword is where things can get asynchronous. Await is like a unary operator: it takes a single argument, an awaitable (an “awaitable” is an asynchronous operation). Await examines that awaitable to see if it has already completed; if the awaitable has already completed, then the method just continues running (synchronously, just like a regular method).
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 returns from the async method.
Later on, when the awaitable completes, it will execute the remainder of the async method. If you’re awaiting a built-in awaitable (such as a task), then the remainder of the async method will execute on a “context” that was captured before the “await” returned.
I like to think of “await” as an “asynchronous wait”. That is to say, the async method pauses until the awaitable is complete (so it waits), but the actual thread is not blocked (so it’s asynchronous).
Awaitables
As I mentioned, “await” takes a single argument - an “awaitable” - which is an asynchronous operation. There are two awaitable types already common in the .NET framework: Task<T> and Task.
There are also other awaitable types: special methods such as “Task.Yield” return awaitables that are not Tasks, and the WinRT runtime (coming in Windows 8) has an unmanaged awaitable type. You can also create your own awaitable (usually for performance reasons), or use extension methods to make a non-awaitable type awaitable.
That’s all I’m going to say about making your own awaitables. I’ve only had to write a couple of awaitables in the entire time I’ve used async/await. If you want to know more about writing your own awaitables, see the Parallel Team Blog or Jon Skeet’s Blog.
One important point about awaitables is this: it is the type that is awaitable, not the method returning the type. In other words, you can await the result of an async method that returns Task … because the method returns Task, not because it’s async. So you can also await the result of a non-async method that returns Task:
public async Task NewStuffAsync()
{
// Use await and have fun with the new stuff.
await ...
}
public Task MyOldTaskParallelLibraryCode()
{
// Note that this is not an async method, so we can't use await in here.
...
}
public async Task ComposeAsync()
{
// We can await Tasks, regardless of where they come from.
await NewStuffAsync();
await MyOldTaskParallelLibraryCode();
}
Tip: If you have a very simple asynchronous method, you may be able to write it without using the await keyword (e.g., using Task.FromResult). If you can write it without await, then you should write it without await, and remove the async keyword from the method. A non-async method returning Task.FromResult is more efficient than an async method returning a value.
Return Types
Async methods can return Task<T>, Task, or void. In almost all cases, you want to return Task<T> or Task, and return void only when you have to.
Why return Task<T> or Task? Because they’re awaitable, and void is not. So if you have an async method returning Task<T> or Task, then you can pass the result to await. With a void method, you don’t have anything to pass to await.
You have to return void when you have async event handlers.
You can also use async void for other “top-level” kinds of actions - e.g., a single “static async void MainAsync()” for Console programs. However, this use of async void has its own problem; see Async Console Programs. The primary use case for async void methods is event handlers.
Returning Values
Async methods returning Task or void do not have a return value. Async methods returning Task<T> must return a value of type T:
public async Task<int> CalculateAnswer()
{
await Task.Delay(100); // (Probably should be longer...)
// Return a type of "int", not "Task<int>"
return 42;
}
This is a bit odd to get used to, but there are good reasons behind this design.
Context
In the overview, I mentioned that when you await a built-in awaitable, then the awaitable will capture the current “context” and later apply it to the remainder of the async method. What exactly is that “context”?
Simple answer:
- If you’re on a UI thread, then it’s a UI context.
- If you’re responding to an ASP.NET request, then it’s an ASP.NET request context.
- Otherwise, it’s usually a thread pool context.
Complex answer:
- If SynchronizationContext.Current is not null, then it’s the current SynchronizationContext. (UI and ASP.NET request contexts are SynchronizationContext contexts).
- Otherwise, it’s the current TaskScheduler (TaskScheduler.Default is the thread pool context).
What does this mean in the real world? For one thing, capturing (and restoring) the UI/ASP.NET context is done transparently:
// WinForms example (it works exactly the same for WPF).
private async void DownloadFileButton_Click(object sender, EventArgs e)
{
// Since we asynchronously wait, the UI thread is not blocked by the file download.
await DownloadFileAsync(fileNameTextBox.Text);
// Since we resume on the UI context, we can directly access UI elements.
resultTextBox.Text = "File downloaded!";
}
// ASP.NET example
protected async void MyButton_Click(object sender, EventArgs e)
{
// Since we asynchronously wait, the ASP.NET thread is not blocked by the file download.
// This allows the thread to handle other requests while we're waiting.
await DownloadFileAsync(...);
// Since we resume on the ASP.NET context, we can access the current request.
// We may actually be on another *thread*, but we have the same ASP.NET request context.
Response.Write("File downloaded!");
}
This is great for event handlers, but it turns out to not be what you want for most other code (which is, really, most of the async code you’ll be writing).
Avoiding Context
Most of the time, you don’t need to sync back to the “main” context. Most async methods will be designed with composition in mind: they await other operations, and each one represents an asynchronous operation itself (which can be composed by others). In this case, you want to tell the awaiter to not capture the current context by calling ConfigureAwait and passing false, e.g.:
private async Task DownloadFileAsync(string fileName)
{
// Use HttpClient or whatever to download the file contents.
var fileContents = await DownloadFileContentsAsync(fileName).ConfigureAwait(false);
// Note that because of the ConfigureAwait(false), we are not on the original context here.
// Instead, we're running on the thread pool.
// Write the file contents out to a disk file.
await WriteToDiskAsync(fileName, fileContents).ConfigureAwait(false);
// The second call to ConfigureAwait(false) is not *required*, but it is Good Practice.
}
// WinForms example (it works exactly the same for WPF).
private async void DownloadFileButton_Click(object sender, EventArgs e)
{
// Since we asynchronously wait, the UI thread is not blocked by the file download.
await DownloadFileAsync(fileNameTextBox.Text);
// Since we resume on the UI context, we can directly access UI elements.
resultTextBox.Text = "File downloaded!";
}
The important thing to note with this example is that each “level” of async method calls has its own context. DownloadFileButton_Click started in the UI context, and called DownloadFileAsync. DownloadFileAsync also started in the UI context, but then stepped out of its context by calling ConfigureAwait(false). The rest of DownloadFileAsync runs in the thread pool context. However, when DownloadFileAsync completes and DownloadFileButton_Click resumes, it does resume in the UI context.
A good rule of thumb is to use ConfigureAwait(false) unless you know you do need the context.
Async Composition
So far, we’ve only considered serial composition: an async method waits for one operation at a time. It’s also possible to start several operations and await for one (or all) of them to complete. You can do this by starting the operations but not awaiting them until later:
public async Task DoOperationsConcurrentlyAsync()
{
Task[] tasks = new Task[3];
tasks[0] = DoOperation0Async();
tasks[1] = DoOperation1Async();
tasks[2] = DoOperation2Async();
// At this point, all three tasks are running at the same time.
// Now, we await them all.
await Task.WhenAll(tasks);
}
public async Task<int> GetFirstToRespondAsync()
{
// Call two web services; take the first response.
Task<int>[] tasks = new[] { WebService1Async(), WebService2Async() };
// Await for the first one to respond.
Task<int> firstTask = await Task.WhenAny(tasks);
// Return the result.
return await firstTask;
}
By using concurrent composition (Task.WhenAll or Task.WhenAny), you can perform simple concurrent operations. You can also use these methods along with Task.Run to do simple parallel computation. However, this is not a substitute for the Task Parallel Library - any advanced CPU-intensive parallel operations should be done with the TPL.
Guidelines
Read the Task-based Asynchronous Pattern (TAP) document. It is extremely well-written, and includes guidance on API design and the proper use of async/await (including cancellation and progress reporting).
There are many new await-friendly techniques that should be used instead of the old blocking techniques. If you have any of these Old examples in your new async code, you’re Doing It Wrong(TM):
| Old | New | Description |
|---|---|---|
| task.Wait | await task | Wait/await for a task to complete |
| task.Result | await task | Get the result of a completed task |
| Task.WaitAny | await Task.WhenAny | Wait/await for one of a collection of tasks to complete |
| Task.WaitAll | await Task.WhenAll | Wait/await for every one of a collection of tasks to complete |
| Thread.Sleep | await Task.Delay | Wait/await for a period of time |
| Task constructor | Task.Run or TaskFactory.StartNew | Create a code-based task |
Next Steps
I have published an MSDN article Best Practices in Asynchronous Programming, which further explains the “avoid async void”, “async all the way” and “configure context” guidelines.
The official MSDN documentation is quite good; they include an online version of the Task-based Asynchronous Pattern document which is excellent, covering the designs of asynchronous methods.
The async team has published an async/await FAQ that is a great place to continue learning about async. They have pointers to the best blog posts and videos on there. Also, pretty much any blog post by Stephen Toub is instructive!
Of course, another resource is my own blog.
Async and Await的更多相关文章
- [译] C# 5.0 中的 Async 和 Await (整理中...)
C# 5.0 中的 Async 和 Await [博主]反骨仔 [本文]http://www.cnblogs.com/liqingwen/p/6069062.html 伴随着 .NET 4.5 和 V ...
- 探索c#之Async、Await剖析
阅读目录: 基本介绍 基本原理剖析 内部实现剖析 重点注意的地方 总结 基本介绍 Async.Await是net4.x新增的异步编程方式,其目的是为了简化异步程序编写,和之前APM方式简单对比如下. ...
- Async和Await异步编程的原理
1. 简介 从4.0版本开始.NET引入并行编程库,用户能够通过这个库快捷的开发并行计算和并行任务处理的程序.在4.5版本中.NET又引入了Async和Await两个新的关键字,在语言层面对并行编程给 ...
- 异步方法的意义何在,Async和await以及Task的爱恨情仇,还有多线程那一家子。
前两天刚感受了下泛型接口的in和out,昨天就开始感受神奇的异步方法Async/await,当然顺路也看了眼多线程那几个.其实多线程异步相关的类单个用法和理解都不算困难,但是异步方法Async/awa ...
- 多线程之异步编程: 经典和最新的异步编程模型,async与await
经典的异步编程模型(IAsyncResult) 最新的异步编程模型(async 和 await) 将 IAsyncInfo 转换成 Task 将 Task 转换成 IAsyncInfo 示例1.使用经 ...
- 浅谈async、await关键字 => 深谈async、await关键字
前言 之前写过有关异步的文章,对这方面一直比较弱,感觉还是不太理解,于是会花点时间去好好学习这一块,我们由浅入深,文中若有叙述不稳妥之处,还请批评指正. 话题 (1)是不是将方法用async关键字标识 ...
- 使用 Async 和 Await 的异步编程(C# 和 Visual Basic)[msdn.microsoft.com]
看到Microsoft官方一篇关于异步编程的文章,感觉挺好,不敢独享,分享给大家. 原文地址:https://msdn.microsoft.com/zh-cn/library/hh191443.asp ...
- 【转】【C#】C# 5.0 新特性——Async和Await使异步编程更简单
一.引言 在之前的C#基础知识系列文章中只介绍了从C#1.0到C#4.0中主要的特性,然而.NET 4.5 的推出,对于C#又有了新特性的增加--就是C#5.0中async和await两个关键字,这两 ...
- C#基础系列——异步编程初探:async和await
前言:前面有篇从应用层面上面介绍了下多线程的几种用法,有博友就说到了async, await等新语法.确实,没有异步的多线程是单调的.乏味的,async和await是出现在C#5.0之后,它的出现给了 ...
- C# Async与Await的使用
这个是.NET 4.5的特性,所以要求最低.NET版本为4.5. 看很多朋友还是使用的Thread来使用异步多线程操作,基本上看不见有使用Async.Await进行异步编程的.各有所爱吧,其实都可以. ...
随机推荐
- IT蓝豹--RecyclerView加载不同view实现效果
本项目由开发者:黄洞洞精心为初学者编辑RecyclerView的使用方法. RecyclerView加载不同view实现效果,支持加载多个view,并且支持用volley获取数据, 项目主要介绍: 初 ...
- 《IT蓝豹》高仿花田ios版标签移动效果
高仿花田ios版标签移动效果,长按每一个item拖动到自己想要位置后,后面位置移动补全效果 . 本项目适合研究gridview拖拽效果的朋友下载. 学习android动画特效. 本项目主要靠DragG ...
- GitHub上最火的40个Android开源项目
http://www.csdn.net/article/2013-05-03/2815127-Android-open-source-projects
- 【SVN】Error running context: 由于目标计算机积极拒绝,无法连接
SVN服务没开启,步骤如下: 1.打开[控制面板]→[管理工具]→[服务]: 2.找到[visual SVN Sever],右击选择[启动]: 3.服务开启后,导入数据就成功了!
- Window10+VS2015+DevExpress.net 15.1.7完美破解(图)
终于找到一个可用的破解工具了,并更新到最新的组件包DevExpressComponents-15.1.7.15288.exe,先看图 破解方法: 先安装DevExpressUniversalTrial ...
- Ubuntu 查询 so 归属的 package
. . . . . 今天 LZ 在运行一个程序的时候,出现找不到 so 库的情况: >$ ./core ./core: error : cannot open shared object fil ...
- 枚举全排列(包括数列中有重复数)的C语言实现
据说是用了DFS的思想--然鹅并不知道这是DFS. 主要就是选取一个数放到数组相应位置上,然后递归的排列剩下的数组,将剩下的数组递归排列完了之后再把数放回去,然后这一层递归就返回了-- 有重复数的话遇 ...
- 运行开源项目,报错Error:(48, 37) 错误: -source 1.6 中不支持 diamond 运算符,请使用-source 7或者更高版本已启用diamond运算符
错误定位 当时并没有弄明白为什么会出错,一脸懵逼相 解决办法: 将source compatibility和target compatibility都改为1.7,重新build就ok了. 错误原因: ...
- Thailand vs Soros
| exchange rate | | Thailand | Soros | |---------------+---------+----------+---------| | | orgin | ...
- PL/SQL安装部署配置(配图解)
PL/SQL安装部署配置 下载好安装包之后,双击exe程序 双击安装程序,出现如下页面 点击[NEXT],出现如下界面 选择[I Accept...],点击[NEXT],出现如下界面 选择安装路径,点 ...