问题
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:
- What if caller calls multiple Begin methods in a row?
- 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