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.
The async pattern using
IAsyncResultwas 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
TaskandTask<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 anIAsyncResultbased asynchronous method pair into aTask<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 returnTask<T>, so the newasync/awaitlanguage support can be used with the framework methods. This is the preferred method moving forward for all asynchronous programming.