The Task-based Asynchronous Pattern enables
developers to define asynchronous functions within a single method definition,
instead of having "begin" and "end" function pairs or separate callbacks. This
makes coding the asynchronous function very intuitive and clear in C# 4.5
(version next). It also integrates mechanism for progress reporting and a
cancellation framework to complete the loop. In the first part of this article,
we will take a look at the approach and components involved in developing
asynchronous functions in C#. I will list out the article in points so you can
take a quick glance-through read.
- Instead of using paired (Begin- and End-) methods, this approach advocates a single method approach
- Advantage of this approach: This results in much more simplified code for asynchronous operations
Putting it together
- "async" modifier - this modifier is applied to the method, or lambda expression or anonymous method - it indicates the method to be asynchronous and signals the possibility of one or more occurrences of the await operator within the method.
- Parameters - the async method specifies the same parameters as the dual method approach. Out and ref parameters are not allowed as arguments to the asynchronous method.
- Naming Convention: the method is named using the convention <methodname>Async
- Return - the async method may return void, Task or Task<TResult>. Void is used only for cases such as event handlers where it is required. Otherwise for methods which return data, return Task<TResult > and return Task if the method does not return anything.
- How a typical asynchronous method definition looks like:
Figure: key structure of an async method
- Exceptions- recommended to be raised only for usage errors (ie error that can be avoided by updating some code). For all other error conditions, the exception should be assigned to the Task that is returned.
- Progress - Long-running operations are typically setup as asynchronous methods to prevent the application from blocking on these long processes. In this scenario, it is helpful to have a mechanism to report the progress back to the user, to give them an expectation of the running time. The IProgress interface can be used for that purpose.
- Cancellation - An option to cancel out the asynchronous method can be provided using the CancellationToken in the asynchronous method. It is optional for implementation and opt-in for callers. This is a very useful feature as the asynchronous methods are usually long running and it's nice to be able to provide the user with an option to cancel out, thus saving resources if not needed any more and also responsive to the end user.
In the first part of this series we took a look at the different components
involved in implementing a task-based asynchronous method in the next version of
C#. In the next parts of the series, we will drill into details and code.