Asynchronous Programming with Async and Await

You can avoid performance bottlenecks and enhance the overall responsiveness of your application by using asynchronous programming. However, traditional techniques for writing asynchronous applications can be complicated, making them difficult to write, debug, and maintain.

bottleneck 瓶颈;障碍物

Visual Studio 2012 introduces a simplified approach, async programming, that leverages asynchronous support in the .NET Framework 4.5 and the Windows Runtime. The compiler does the difficult work that the developer used to do, and your application retains a logical structure that resembles synchronous code. As a result, you get all the advantages of asynchronous programming with a fraction of the effort.

leverage 手段,影响力;杠杆作用;杠杆效率

resemble 类似,像

fraction  分数;部分;小部分;稍微

This topic contains the following sections.

This topic provides an overview of when and how to use async programming and includes links to support topics that contain details and examples.

Async Improves Responsiveness

Asynchrony is essential for activities that are potentially blocking, such as when your application accesses the web. Access to a web resource sometimes is slow or delayed. If such an activity is blocked within a synchronous process, the entire application must wait. In an asynchronous process, the application can continue with other work that doesn't depend on the web resource until the potentially blocking task finishes.

essential 本质;要素;要点;必需品

The following table shows typical areas where asynchronous programming improves responsiveness. The listed APIs from the .NET Framework 4.5 and the Windows Runtime contain methods that support async programming.

Application area

Supporting APIs that contain async methods

Web access

HttpClientSyndicationClient

Working with files

StorageFileStreamWriterStreamReaderXmlReader

Working with images

MediaCaptureBitmapEncoderBitmapDecoder

WCF programming

Synchronous and Asynchronous Operations

Asynchrony proves especially valuable for applications that access the UI thread because all UI-related activity usually shares one thread. If any process is blocked in a synchronous application, all are blocked. Your application stops responding, and you might conclude that it has failed when instead it's just waiting.

conclude 推断;断定;决定

When you use asynchronous methods, the application continues to respond to the UI. You can resize or minimize a window, for example, or you can close the application if you don't want to wait for it to finish.

The async-based approach adds the equivalent of an automatic transmission to the list of options that you can choose from when designing asynchronous operations. That is, you get all the benefits of traditional asynchronous programming but with much less effort from the developer.

equivalent 等价物,相等物

Async Methods Are Easier to Write

The Async and Await keywords in Visual Basic and the async and await keywords in C# are the heart of async programming. By using those two keywords, you can use resources in the .NET Framework or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. Asynchronous methods that you define by using async and await are referred to as async methods.

The following example shows an async method. Almost everything in the code should look completely familiar to you. The comments call out the features that you add to create the asynchrony.

You can find the complete example file at the end of this topic, and you can download the sample from Async Sample: Example from "Asynchronous Programming with Async and Await".

// Three things to note in the signature:
// - The method has an async modifier.
// - The return type is Task or Task<T>. (See "Return Types" section.)
// Here, it is Task<int> because the return statement returns an integer.
// - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient(); // GetStringAsync returns a Task<string>. That means that when you await the
// task you'll get a string (urlContents).
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com"); // You can do work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork(); // The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from getStringTask.
string urlContents = await getStringTask; // The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents.Length;
}

If AccessTheWebAsync doesn't have any work that it can do between calling GetStringAsync and awaiting its completion, you can simplify your code by calling and awaiting in the following single statement.

string urlContents = await client.GetStringAsync();

总结:

The following characteristics summarize what makes the previous example an async method.

  • The method signature includes an Async or async modifier.

  • The name of an async method, by convention, ends with an "Async" suffix.

  • The return type is one of the following types:

    • Task if your method has a return statement in which the operand has type TResult.

    • Task if your method has no return statement or has a return statement with no operand.

    • Void (a Sub in Visual Basic) if you're writing an async event handler.

    For more information, see "Return Types and Parameters" later in this topic.

  • The method usually includes at least one await expression, which marks a point where the method can't continue until the awaited asynchronous operation is complete. In the meantime, the method is suspended, and control returns to the method's caller. The next section of this topic illustrates what happens at the suspension point.

illustrate 阐明,举例说明;图解

In async methods, you use the provided keywords and types to indicate what you want to do, and the compiler does the rest, including keeping track of what must happen when control returns to an await point in a suspended method. Some routine processes, such as loops and exception handling, can be difficult to handle in traditional asynchronous code. In an async method, you write these elements much as you would in a synchronous solution, and the problem is solved.

routine  日常的;例行的

For more information about asynchrony in previous versions of the .NET Framework, see TPL and Traditional .NET Framework Asynchronous Programming.

What Happens in an Async Method

The most important thing to understand in asynchronous programming is how the control flow moves from method to method. The following diagram leads you through the process.

diagram 图表;图解

The numbers in the diagram correspond to the following steps.

  1. An event handler calls and awaits the AccessTheWebAsync async method.

  2. AccessTheWebAsync creates an HttpClient instance and calls the GetStringAsync asynchronous method to download the contents of a website as a string.

  3. Something happens in GetStringAsync that suspends its progress. Perhaps it must wait for a website to download or some other blocking activity. To avoid blocking resources, GetStringAsync yields control to its caller,AccessTheWebAsync.

    GetStringAsync returns a Task where TResult is a string, and AccessTheWebAsync assigns the task to the getStringTask variable. The task represents the ongoing process for the call to GetStringAsync, with a commitment to produce an actual string value when the work is complete.

  4. Because getStringTask hasn't been awaited yet, AccessTheWebAsync can continue with other work that doesn't depend on the final result from GetStringAsync. That work is represented by a call to the synchronous method DoIndependentWork.

  5. DoIndependentWork is a synchronous method that does its work and returns to its caller.

  6. AccessTheWebAsync has run out of work that it can do without a result from getStringTask. AccessTheWebAsync next wants to calculate and return the length of the downloaded string, but the method can't calculate that value until the method has the string.

Note:If GetStringAsync (and therefore getStringTask) is complete before AccessTheWebAsync awaits it, control remains in AccessTheWebAsync. The expense of suspending and then returning to AccessTheWebAsyncwould be wasted if the called asynchronous process (getStringTask) has already completed and AccessTheWebSync doesn't have to wait for the final result.

Inside the caller (the event handler in this example), the process is repeated. The caller might do other work that doesn't depend on the result from AccessTheWebAsync before awaiting that result, or the caller might await immediately. When the event handler reaches an await expression, the application focuses on the completion of GetStringAsync. The event handler is waiting for AccessTheWebAsync, and AccessTheWebAsync is waiting for GetStringAsync.

  • 7.GetStringAsync completes and produces a string result. The string result isn't returned by the call to GetStringAsync in the way that you might expect. (Remember that the method already returned a task in step 3.) Instead, the string result is stored in the task that represents the completion of the method, getStringTask. The await operator retrieves the result from getStringTask. The assignment statement assigns the retrieved result to urlContents.
  • 8.When AccessTheWebAsync has the string result, the method can calculate the length of the string. Then the work of AccessTheWebAsync is also complete, and the waiting event handler can resume. In the full example at the end of the topic, you can confirm that the event handler retrieves and prints the value of the length result.

if you are new to asynchronous programming, take a minute to consider the difference between synchronous and asynchronous behavior. A synchronous method returns when its work is complete (step 5), but an async method returns a task value when its work is suspended (steps 3 and 6). When the async method eventually completes its work, the task is marked as completed and the result, if any, is stored in the task.

For more information about control flow, see Control Flow in Async Programs (C# and Visual Basic).

API Async Methods

You might be wondering where to find methods such as GetStringAsync that support async programming. The .NET Framework 4.5 contains many members that work with async and await. You can recognize these members by the "Async" suffix that’s attached to the member name and a return type of Task or Task. For example, the System.IO.Stream class contains methods such as CopyToAsyncReadAsync, and WriteAsync alongside the synchronous methods CopyToRead, and Write.

The Windows Runtime also contains many methods that you can use with async and await in Windows Store apps. For more information and example methods, see Quickstart: using the await operator for asynchronous programmingAsynchronous programming (Windows Store apps), and WhenAny: Bridging between the .NET Framework and the Windows Runtime (C# and Visual Basic).

Threads

Async methods are intended to be non-blocking operations. An await expression in an async method doesn’t block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available.

The async-based approach to asynchronous programming is preferable to existing approaches in almost every case. In particular, this approach is better than BackgroundWorker for IO-bound operations because the code is simpler and you don't have to guard against race conditions. In combination with Task.Run, async programming is better than BackgroundWorker for CPU-bound operations because async programming separates the coordination details of running your code from the work that Task.Run transfers to the threadpool.

guard against防止,提防   race condition竞争条件   coordination协调,调和;对等,同等

Async and Await

If you specify that a method is an async method by using an Async or async modifier, you enable the following two capabilities.

  • The marked async method can use Await or await to designate suspension points. The await operator tells the compiler that the async method can't continue past that point until the awaited asynchronous process is complete. In the meantime, control returns to the caller of the async method.

    The suspension of an async method at an await expression doesn't constitute an exit from the method, and finally blocks don’t run.

designate 指定;指派;标出;把…定名为    suspension悬浮;暂停;停职     constitute组成,构成;建立;任命

  • The marked async method can itself be awaited by methods that call it.

An async method typically contains one or more occurrences of an await operator, but the absence of await expressions doesn’t cause a compiler error. If an async method doesn’t use an await operator to mark a suspension point, the method executes as a synchronous method does, despite the async modifier. The compiler issues a warning for such methods.

absence 没有;缺乏;缺席;不注意   despite尽管,不管

Async, async, Await, and await are contextual keywords. For more information and examples, see the following topics:

Return Types and Parameters

In .NET Framework programming, an async method typically returns a Task or a Task. Inside an async method, an await operator is applied to a task that's returned from a call to another async method.

You specify Task as the return type if the method contains a Return (Visual Basic) or return (C#) statement that specifies an operand of type TResult.

You use Task as the return type if the method has no return statement or has a return statement that doesn't return an operand.

The following example shows how you declare and call a method that returns a Task or a Task.

// Signature specifies Task<TResult>
async Task<int> TaskOfTResult_MethodAsync()
{
int hours;
// . . .
// The body of the method should contain one or more await expressions. // Return statement specifies an integer result.
return hours;
} // Calls to TaskOfTResult_MethodAsync from another async method.
private async void CallTaskTButton_Click(object sender, RoutedEventArgs e)
{
Task<int> returnedTaskTResult = TaskOfTResult_MethodAsync();
int intResult = await returnedTaskTResult;
// or, in a single statement
//int intResult = await TaskOfTResult_MethodAsync();
} // Signature specifies Task
async Task Task_MethodAsync()
{
// . . .
// The body of the method should contain one or more await expressions. // The method has no return statement.
} // Calls to Task_MethodAsync from another async method.
private async void CallTaskButton_Click(object sender, RoutedEventArgs e)
{
Task returnedTask = Task_MethodAsync();
await returnedTask;
// or, in a single statement
//await Task_MethodAsync();
}

Each returned task represents ongoing work. A task encapsulates information about the state of the asynchronous process and, eventually, either the final result from the process or the exception that the process raises if it doesn't succeed.

An async method can also be a Sub method (Visual Basic) or have a void return type (C#). This return type is used primarily to define event handlers, where a void return type is required. Async event handlers often serve as the starting point for async programs.

An async method that’s a Sub procedure or that has a void return type can’t be awaited, and the caller of a void-returning method can't catch any exceptions that the method throws.

An async method can't declare ByRef parameters in Visual Basic or ref or out parameters in C#, but the method can call methods that have such parameters.

For more information and examples, see Async Return Types (C# and Visual Basic). For more information about how to catch exceptions in async methods, see try-catch (C# Reference) or Try...Catch...Finally Statement (Visual Basic).

Asynchronous APIs in Windows Runtime programming have one of the following return types, which are similar to tasks:

For more information and an example, see Quickstart: using the await operator for asynchronous programming.

Name Convention

By convention, you append "Async" to the names of methods that have an Async or async modifier.

You can ignore the convention where an event, base class, or interface contract suggests a different name. For example, you shouldn’t rename common event handlers, such as Button1_Click.

Related Topics

Title

Description

Sample

Walkthrough: Accessing the Web by Using Async and Await (C# and Visual Basic)

Shows how to convert a synchronous WPF solution to an asynchronous WPF solution. The application downloads a series of websites.

Async Sample: Accessing the Web Walkthrough (C# and Visual Basic)

How to: Extend the Async Walkthrough by Using Task.WhenAll (C# and Visual Basic)

Adds Task.WhenAll to the previous walkthrough. The use of WhenAll starts all the downloads at the same time.

 

How to: Make Multiple Web Requests in Parallel by Using Async and Await (C# and Visual Basic)

Demonstrates how to start several tasks at the same time.

Async Sample: Make Multiple Web Requests in Parallel (C# and Visual Basic)

Async Return Types (C# and Visual Basic)

Illustrates the types that async methods can return and explains when each type is appropriate.

 

Control Flow in Async Programs (C# and Visual Basic)

Traces in detail the flow of control through a succession of await expressions in an asynchronous program.

Async Sample: Control Flow in Async Programs (C# and Visual Basic)

Fine Tuning Your Async Application (C# and Visual Basic)

Shows how to add the following functionality to your async solution:

Async Sample: Fine Tuning Your Application (C# and Visual Basic)

Handling Reentrancy in Async Apps (C# and Visual Basic)

Shows how to handle cases in which an active asynchronous operation is restarted while it’s running.

 

WhenAny: Bridging between the .NET Framework and the Windows Runtime (C# and Visual Basic)

Shows how to bridge between Task types in the .NET Framework and IAsyncOperations in the Windows Runtime so that you can use WhenAny``1 with a Windows Runtime method.

Async Sample: Bridging between .NET and Windows Runtime (AsTask and WhenAny)

Async Cancellation: Bridging between the .NET Framework and the Windows Runtime (C# and Visual Basic)

Shows how to bridge between Task types in the .NET Framework and IAsyncOperations in the Windows Runtime so that you can use CancellationTokenSource with a Windows Runtime method.

Async Sample: Bridging between .NET and Windows Runtime (AsTask & Cancellation)

Using Async for File Access (C# and Visual Basic)

Lists and demonstrates the benefits of using async and await to access files.

 

Walkthrough: Using the Debugger with Async Methods

Demonstrates the control flow at an await statement, and demonstrates the behavior of the Step Into, Step Over, and Step Out commands within async methods.

 

Task-based Asynchronous Pattern (TAP)

Describes a new pattern for asynchrony in the .NET Framework. The pattern is based on the Task and Tasktypes.

 

Quickstart: Calling asynchronous APIs in C# or Visual Basic

Shows how to use async and await in a Windows Store app.

 

Asynchronous programming (Windows Store apps)

Provides an overview of asynchronous programming in the Windows Runtime.

 

Async Videos on Channel 9

Provides links to a variety of videos about async programming.

编程概念--使用async和await的异步编程的更多相关文章

  1. 四、C# 5.0 新特性——Async和Await使异步编程更简单

    一.引言 .NET 4.5 的推出,对于C#又有了新特性的增加--就是C#5.0中async和await两个关键字,这两个关键字简化了异步编程,之所以简化了,还是因为编译器给我们做了更多的工作,下面就 ...

  2. 使用 Async 和 Await 的异步编程(C# 和 Visual Basic)[msdn.microsoft.com]

    看到Microsoft官方一篇关于异步编程的文章,感觉挺好,不敢独享,分享给大家. 原文地址:https://msdn.microsoft.com/zh-cn/library/hh191443.asp ...

  3. 【转】【C#】C# 5.0 新特性——Async和Await使异步编程更简单

    一.引言 在之前的C#基础知识系列文章中只介绍了从C#1.0到C#4.0中主要的特性,然而.NET 4.5 的推出,对于C#又有了新特性的增加--就是C#5.0中async和await两个关键字,这两 ...

  4. 使用Async和Await进行异步编程(C#版 适用于VS2015)

    你可以使用异步编程来避免你的应用程序的性能瓶颈并且加强总体的响应.然而,用传统的技术来写异步应用是复杂的,同时编写,调试和维护都很困难. VS2012介绍了简单的方法,那就是异步编程,它在.Net F ...

  5. 使用Async和Await进行异步编程(C#版 适用于VS2015) z

    你可以使用异步编程来避免你的应用程序的性能瓶颈并且加强总体的响应.然而,用传统的技术来写异步应用是复杂的,同时编写,调试和维护都很困难. VS2012介绍了简单的方法,那就是异步编程,它在.Net F ...

  6. Async和Await进行异步编程

    使用Async和Await进行异步编程(C#版 适用于VS2015) 你可以使用异步编程来避免你的应用程序的性能瓶颈并且加强总体的响应.然而,用传统的技术来写异步应用是复杂的,同时编写,调试和维护都很 ...

  7. 【C#复习总结】 Async 和 Await 的异步编程

    谈到异步,必然要说下阻塞,在知乎上看到了网友举的例子非常省动,在这里我引用下. 怎样理解阻塞非阻塞与同步异步的区别? 老张爱喝茶,废话不说,煮开水. 出场人物:老张,水壶两把(普通水壶,简称水壶:会响 ...

  8. 转:[你必须知道的异步编程]C# 5.0 新特性——Async和Await使异步编程更简单

    本专题概要: 引言 同步代码存在的问题 传统的异步编程改善程序的响应 C# 5.0 提供的async和await使异步编程更简单  async和await关键字剖析 小结 一.引言 在之前的C#基础知 ...

  9. [你必须知道的异步编程]C# 5.0 新特性——Async和Await使异步编程更简单

    本专题概要: 引言 同步代码存在的问题 传统的异步编程改善程序的响应 C# 5.0 提供的async和await使异步编程更简单  async和await关键字剖析 小结 一.引言 在之前的C#基础知 ...

随机推荐

  1. 使用Dreamweaver批量删除PHP项目中的单行注释和多行注释

    1.删除单行注释 打开Dreamweaver的查找工具,选择正则替换如图: 里面的//.*是正则匹配单行注释的表达式   2.删除多行注释 同样用正则查找匹配,直接上图咯:  其中正则表达式为/\*[ ...

  2. iomanip,setw(),setw: undeclared identifier

    今天使用setw(),提示setw: undeclared identifier,上网查了下,原来是没有包含头文件iomanip,现摘录如下: iomanip #include <iomanip ...

  3. ADO和ADO.NET的区别

    1. ADO与ADO.NET简介 ADO与ADO.NET既有相似也有区别,他们都能够编写对数据库服务器中的数据进行访问和操作的应用程序,并且易于使用.高速度.低内存支出和占用磁盘空间较少,支持用于建立 ...

  4. PDF合并

    要求:将多个table导出到一个PDF里,然后打印. 问题分析:要求将四个table放一个PDF打印,四个table的列各不相同,第一个是表头,其他三个是列表,列比表头多很多,如果直接生成一个exce ...

  5. 【分享】SQL Server优化50法

    虽然查询速度慢的原因很多,但是如果通过一定的优化,也可以使查询问题得到一定程度的解决. 查询速度慢的原因很多,常见如下几种: 没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设计的缺陷) I/ ...

  6. go语言使用protobuf

    网上为什么充斥着大量几乎一模一样而且不正确的教程??? 妈的打开一个关于golang和protobuf的教程,无非都是protobuf多么多么牛逼,xml多么多么傻逼,然后就是怎么安装protobuf ...

  7. Python系统调用——运行其他程序

    转载:http://blog.csdn.net/ssihc0/article/details/7738527 在Python中可以方便地使用os模块运行其他的脚本或者程序,这样就可以在脚本中直接使用其 ...

  8. js实现网页图片延时加载的原理和代码 提高网站打开速度

    有时我们看到一些大型网站,页面如果有很多图片的时候,当你滚动到相应的行时,当前行的图片才即时加载的,这样子的话页面在打开只加可视区域的图片,而其它隐藏的图片则不加载,一定程序上加快了页面加载的速度,对 ...

  9. jQuery中的join方法

    和JS 中的JOIN 方法一样,将一数组按照JOIN的参数连接起来.比如: var arr = [ "a", "b", "c", " ...

  10. BZOJ 4123 [Baltic2015] Hacker 解题报告

    首先,Alice 会选择一个长度为 $\lfloor\frac{n+1}{2}\rfloor$ 的区间,我们把这个长度记为 $len$. 有这么一个结论:令 $F_i$ 为覆盖 $i$ 点的所有长度为 ...