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 ...
随机推荐
- hibernate的一种报错
Exception in thread "main" java.lang.NoClassDefFoundError: javax/tools/StandardJavaFileMan ...
- rpc使用JUnit模块测试设计的方法及常见问题
RPC:Remote Procedure Call 远程过程调用 Wikipedia:http://en.wikipedia.org/wiki/Remote_Procedure_Call 百度百科:h ...
- 如何处理C#的HttpWebResponse的GetResponse中的超时异常
程序中,有时会遇到超时的异常,需要进行处理,用一般的try...catch(Exception ex)...会发现ex没有status属性,此时使用WebException捕获异常: try { re ...
- 关于CSS三列Float布局任务
任务目标 掌握HTML/CSS布局的概念 掌握盒模型的概念 掌握position与float的概念以及在布局时的用法 任务描述 使用 HTML 与 CSS 按照示意图;实现三栏式布局. 左右两栏宽度固 ...
- Fiddler-2 Fiddler抓包原理
1 fiddler抓包是在 客户端和服务器之间建立一个代理服务器,监听本机发出的请求和服务器返回的响应结果. 截一张官网的图: 2 启动fiddler之前,[dinghanhua]先来看一下代理服务器 ...
- 弹性盒子之wap端布局
发现移动端用弹性盒子布局起来更加的方便,box-flex:val;特别是图文展示的时候,如下面的 <!DOCTYPE html> <html> <head> < ...
- sql case when then else end
我们都知道SQL中适用case when then来转化数据库中的信息 比如 select (case sex when 0 then '男' else '女' end) AS sex from st ...
- Qt中sizeof
class a{ int d; // virtual void ssss(); }; qDebug() <<sizeof(a) << sizeof(int) << ...
- hdu 2074
ps:WA了好多次...因为首先是n=1的情况,其次是中心花色和外花色,中心花色也有可能是最外层花色....很无语. 然后就是格式问题咯. 代码 #include "stdio.h" ...
- Java并发编程学习笔记(二)——对象的共享
主要概念:可见性.重排序.失效数据.最低安全性.发布.逸出.线程封闭(Ad-hoc.栈封闭.ThreadLocal类).不变性.Final域.事实不可变对象. 1.在没有同步的情况下,编译器.处理器以 ...