Microsoft, over the life of the .NET framework, has used many different Asynchronous patterns. This post will look at three of them and hopefully, in the process, shed some light on options available to .NET developers trying to write their own asynchronous code.
In .NET 1.x Microsoft used the Begin/End pattern. This pattern had three major pieces:
- The Begin method. This method begins an operation asynchronously and creates an IAsyncResult token for the operation.
- The IAsyncResult. This token indicates if an asynchronous operation is finished. It is consumed by the End method.
- The End method. This method returns the result of an asynchronous operation. If necessary, it will block execution until the result is ready.
A good example of this pattern is BeginInvoke and EndInvoke on delegates.
In .NET 2.0 Microsoft used the Async/Completed pattern which also had three pieces.
- A Method with an ‘Async’ suffix. This method starts the asynchronous operation
- An event with a ‘Completed’ suffix. This event is fired when the asynchronous operation completes.
- An EventArgs. This is passed to the Completed event and contains the result of the operation and any exceptions that may have occurred.
A good example of a class using this pattern is WebClient
In .NET 4.0 Microsoft began using the Async/Await pattern that has three pieces as well.
- ‘async’ keyword in the signature of the method that will be making the asynchronous call.
- ‘await’ keyword in front of an awaitable operation (typically a Task but doesn’t have to be).
- Task or Task
return type from the async method. Token used by the caller to know when the async method has completed.
A good example of a class using this pattern is HttpClient.