新库中的异步与非异步方法
在.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.
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