What are the strengths of the IAsyncResult pattern? [closed]

送分小仙女□ 提交于 2021-02-08 06:19:38

问题


I feel that many classes (e.g. TcpClient, UdpClient, HttpListener) would've been much easier to understand and use if they were event driven. And IAsyncResult pattern is excessively hard to implement because it opens you to all kinds of weird use cases:

  1. What if caller calls multiple Begin methods in a row?
  2. What if caller mixes Begin and regular methods?

And so on. Nevertheless, Microsoft has chosen to use it in most places. Why?

Edit: Please focus the discussion on .NET 2.0 as that's what I have to work with.


回答1:


And so on. Nevertheless, Microsoft has chosen to use it in most places. Why?

The async pattern using IAsyncResult was the original asynchronous programming pattern used within the Framework. It has few advantages, and the complexity has led to new patterns being developed over time.

Event Asynchronous Programming (EAP) was introduced later (where you have a "Begin" method with a completion event). This solved a lot of the complexity, but was still difficult to use in many situations, as you have to split your logic into multiple methods still.

However, the current asynchronous pattern is based around .NET 4's Task and Task<T> class, and provides huge advantages, especially when coupled with C# 5's async/await support. Luckily, TaskFactory.FromAsync can be used to easily wrap an IAsyncResult based asynchronous method pair into a Task<T> automatically, so the new patterns can be used. .NET 4.5 has added new versions of many of the framework's asynchronous methods which return Task<T>, so the new async/await language support can be used with the framework methods. This is the preferred method moving forward for all asynchronous programming.




回答2:


This pattern doesn't have many strengths.

In .Net 1.0, before generics and lambda expressions, this was the only asynchronous pattern available.

The more modern task-based pattern is much nicer for a number of reasons, including type-safety, simpler error handling, continuations, When*() methods, and others.



来源:https://stackoverflow.com/questions/12750532/what-are-the-strengths-of-the-iasyncresult-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!