新库中的异步与非异步方法 [英] async vs non-async methods in a new library

查看:75
本文介绍了新库中的异步与非异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET 4.5中,异步和非异步对中现在有很多方法,例如Flush()FlushAsync().理想情况下,在可能的情况下,I/O交互始终应该是异步的(如果您确实愿意,可以始终使用.Wait()进行阻止),但是由于向后兼容性,显然必须保留非异步(阻止)版本.

In .NET 4.5, there are many methods that now come in async and non-async pairs, such as Flush() and FlushAsync(). Ideally I/O interactions would always be asynchronous where possible (you can always block with .Wait() if you really want to), but the non-async (blocking) versions obviously need to remain due to backwards compatibility.

推出一个没有向后兼容性限制的全新库时,是否有任何理由要包含非异步方法?

When rolling out a completely new library that has no backwards compatibility restrictions, is there any reason why one would include the non-async methods?

推荐答案

异步方法通常会带来一些开销,因为编译器会生成状态机,从而导致大量额外的代码.如果您不使用async方法,则不会被忽略,因此可以避免这种花费.

Async methods usually have a cost associated with them as there is a state machine generated by the compiler which results in quite a bit of extra code. If you are not using the async methods they won't be jitted so you avoid that cost.

如果使用async版本并仅调用Wait(),则可能会冒着

If you use the async version and simply call Wait() you are risking a deadlock and also you would incur an extra context switch once the async operation completes. So overall the result would perform slightly worse.

现在,您获得的所有异常都将包装在AggregatedException中,因此在异常处理中也将进行额外的工作.看看异步性能:了解异步和等待的代价

Also any exceptions you get will now be wrapped in an AggregatedException so there will be extra work in exception processing as well. Have a look at Async Performance: Understanding the Costs of Async and Await

这篇关于新库中的异步与非异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆