Async/Await - Best Practices in Asynchronous Programming
https://msdn.microsoft.com/en-us/magazine/jj991977.aspx
Figure 1 Summary of Asynchronous Programming Guidelines
| Name | Description | Exceptions |
| Avoid async void | Prefer async Task methods over async void methods | Event handlers |
| Async all the way | Don’t mix blocking and async code | Console main method |
| Configure context | Use ConfigureAwait(false) when you can | Methods that require context |
Avoid Async Void
You should prefer "async Task" to "async void". Async Task methods enable easier error-handling(propagate up or not), composability (Task.waitAll ...) and testability. The exception to this guideline is asynchronous event handlers, which must return void. This exception includes methods that are logically event handlers even if they’re not literally event handlers (for example, ICommand.Execute implementations).
Async All the Way
"Async all the way” means that you shouldn’t mix synchronous and asynchronous code without carefully considering the consequences. In particular, it’s usually a bad idea to block on async code by calling Task.Wait or Task.Result. This is an common problem for programmers who try to convert just a small part of their application and wrapping it in a synchronous API so the rest of the application is isolated from the changes. Unfortunately, this can cause deadlocks, in the case of GUI or ASP.NET (not if in a console application). The exception semantic for await and Task.Wait is also different, Exception versus AggregateException. So do not do this except in the Main method for console applications.
Figure 5 The “Async Way” of Doing Things
| To Do This … | Instead of This … | Use This |
| Retrieve the result of a background task | Task.Wait or Task.Result | await |
| Wait for any task to complete | Task.WaitAny | await Task.WhenAny |
| Retrieve the results of multiple tasks | Task.WaitAll | await Task.WhenAll |
| Wait a period of time | Thread.Sleep | await Task.Delay |
Configure Context
Await require context, see the following code, if you swap the commented-out lines in DelayAsync, it will not deadlock,
public static class DeadlockDemo
{
private static async Task DelayAsync()
{
await Task.Delay(1000);
//await Task.Delay(1000).ConfigureAwait(continueOnCapturedContext: false);
} // This method causes a deadlock when called in a GUI or ASP.NET context.
public static void Test()
{ // Start the delay.
var delayTask = DelayAsync(); // Wait for the delay to complete.
delayTask.Wait();
}
}
This technique is particularly useful if you need to gradually convert an application from synchronous to asynchronous.
You should not use ConfigureAwait when you have code after the await in the method that needs the context.
Async/Await - Best Practices in Asynchronous Programming的更多相关文章
- Async/Await - Best Practices in Asynchronous Programming z
These days there’s a wealth of information about the new async and await support in the Microsoft .N ...
- [译]Async/Await - Best Practices in Asynchronous Programming
原文 避免async void async void异步方法只有一个目的:使得event handler异步可行,也就是说async void只能用于event handler. async void ...
- Best Practices in Asynchronous Programming
http://blog.stephencleary.com/ http://blogs.msdn.com/b/pfxteam/
- 将 async/await 异步代码转换为安全的不会死锁的同步代码
在 async/await 异步模型(即 TAP Task-based Asynchronous Pattern)出现以前,有大量的同步代码存在于代码库中,以至于这些代码全部迁移到 async/awa ...
- Async/Await FAQ
From time to time, I receive questions from developers which highlight either a need for more inform ...
- 异步模式:Callbacks, Promises & Async/Await
[译]异步JavaScript的演变史:从回调到Promises再到Async/Await https://www.i-programmer.info/programming/theory/8864- ...
- C#的多线程——使用async和await来完成异步编程(Asynchronous Programming with async and await)
https://msdn.microsoft.com/zh-cn/library/mt674882.aspx 侵删 更新于:2015年6月20日 欲获得最新的Visual Studio 2017 RC ...
- Asynchronous programming with async and await (C#)
Asynchronous Programming with async and await (C#) | Microsoft Docs https://docs.microsoft.com/en-us ...
- .NET 基于任务的异步模式(Task-based Asynchronous Pattern,TAP) async await
本文内容 概述 编写异步方法 异步程序中的控制流 API 异步方法 线程 异步和等待 返回类型和参数 参考资料 下载 Demo 下载 Demo TPL 与 APM 和 EAP 结合(APM 和 EAP ...
随机推荐
- Loadrunner11安装和破解方法
公司很多项目都在做性能测试,打算把性能测试学习下.(不懂还可以问问公司大神,这么好的机会不要错过了O(∩_∩)O哈哈~)用了二周实践看了性能测试方面一些基本术语和概念,一直都还没自己动手实践,光看基本 ...
- 基本矩阵运算的Java实现
一: 矩阵的加法与减法 规则:矩阵的加法与减法要求两个矩阵的行列完全相等,方可以完成两个矩阵的之间的运算. 举例说明如下 二:矩阵的乘法 规则:矩阵的乘法要求两个矩阵符合A(mx k), B( ...
- DataTable转Json字符串(使用Newtonsoft.Json.dll)
DataTable转Json字符串(使用Newtonsoft.Json.dll) 在需要把DataTable转为Json字符串时,自己手动拼接太麻烦,而且容易出错,费时费力,使用Newtonsoft. ...
- python获取指定时间段内的随机不重复的时间点
上篇 <python时间时分秒与秒数的互相转换>http://www.cnblogs.com/gayhub/p/6154707.html 提到了把时间转成秒数的方法, 这篇写写转换成秒数后 ...
- Android中的onActivityResult和setResult方法的使用
如果你想在Activity中得到新打开Activity关闭后返回的数据,你需要使用系统提供的startActivityForResult(Intent intent,int requestCode)方 ...
- Android 数据库管理— — —删除数据
package com.example.datebasetest; import android.content.ContentValues;import android.database.sqlit ...
- K均值聚类算法的MATLAB实现
1.K-均值聚类法的概述 之前在参加数学建模的过程中用到过这种聚类方法,但是当时只是简单知道了在matlab中如何调用工具箱进行聚类,并不是特别清楚它的原理.最近因为在学模式识别,又重新接触了这 ...
- 北大poj-1011
木棒 Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 136132 Accepted: 32036 Description ...
- 关于docker容器是怎样建立新的namespace的。
最近博客收到了一封交流的私信,感谢您的关注:现在就我理解的docker建立容器时namespace的建立问题做一个 个人的回答: 一,从原理角度来讲: docker创建container,说白了就是l ...
- 数组的sizeof
数组的sizeof值等于数组所占用的内存字节数,如: char a1[] = "abc"; int a2[3]; sizeof( a1 ); // 结果为4,字符 末尾还存在 ...