The BCL has a bunch of APIs which provide asynchronous versions of operations in the form of either Beginxxx/Endxxx or XyzCompleted, the former known as Asynchronous Programming Model(APM) and the latter known as Event Based Asynchronous Pattern (EAP). TPL provides a nice abstraction for performing asynchronous operations as Tasks using delegates, but what can you do for working with these existing BCL classes which already have an async version?
Here is an example.
Let's say we need to download some data from the web and save it to a file, you would typically use the WebClient class and write something like this today (wrapped in a method of course)
- WebClient client = new WebClient();
- client.DownloadDataAsync(new Uri("http://www.bing.com"));
- client.DownloadDataCompleted += new DownloadDataCompletedEventHandler((s, e) =>
- if (e.Error != null)
- throw e.Error;
- if (!e.Cancelled)
- using (FileStream fs = new FileStream("bing.htm", FileMode.CreateNew))
Yuck not very pretty is it! It's kinda smelly and looking at the code, it doesn't really capture the essense of what we are trying to do, besides if the client were to call a method which does this work, we'd have to ensure that the client thread blocks till the continuation completes or conversely provide a mechanism such as a WaitHandle that the client can wait on, not very expressive is it?
Let's see how we can achieve the same results using the Task API.
- private static TaskCompletionSource<byte> CreateSource(object state)
- return new TaskCompletionSource<byte>(state);
- private static void SetCompletionSource<T>(
- TaskCompletionSource<T> tcs,
- AsyncCompletedEventArgs e,
- Func<T> getResult)
- if (e.UserState == tcs)
- if (e.Cancelled)
- if (e.Error != null) tcs.TrySetException(e.Error);
- public static Task<byte> DownloadBytesTask(this WebClient webClient, string uri)
- var source = CreateSource(uri);
- DownloadDataCompletedEventHandler handler = null;
- handler = (object s, DownloadDataCompletedEventArgs e) =>
- SetCompletionSource(source, e, () => e.Result);
- webClient.DownloadDataCompleted -= handler;
- webClient.DownloadDataAsync(new Uri(uri), source);
- webClient.DownloadDataCompleted += handler;
- return source.Task;
We've wrapped up the async network operation into a Task as an extension method.
Let's dig in a little...
In DownloadBytesTask, we first create a TaskCompletionSource which provides a mechanism to create a Task to hand out to consumers such that the only legal state modification to the Task can be performed via the methods available on the TaskCompletionSource itself and not on the instance of the Task directly, this is precisely the behavior needed for a Task that is downloading content from the web asynchronously;it doesn't make sense for the client to explicitly start such a Task which has already started downloading data and such an operation should really be considered illegal, TaskCompletionSource enables this behavior.
In the callback we call SetCompletionSource which is responsible for transitioning the state of the Task based on the results of the asynchronous operation such as whether it errored out, or completed or whether it was cancelled.
We then proceed to start the asynchronous download by calling DownloadDataAsync method of the WebClient instance.
Couple of things to note:
- The callback has been unhooked from the event in the callback to ensure that we don't have a memory leak.
- The Task has already started since "DownloadDataAsync" has already been invoked, and it is this started Task that we return from the method.
The client can now perform the asynchronous download and saving of content like so:
- public class Program
- public static Task WriteToFileTask(string fileName, byte bytes)
- FileStream fs = new FileStream(fileName, FileMode.CreateNew);
- var task = Task.Factory.FromAsync(fs.BeginWrite, fs.EndWrite, bytes, 0, bytes.Length, null);
- return task;
- static void Main(string args)
- WebClient wc = new WebClient();
- var task = wc.DownloadBytesTask("http://www.bing.com/");
- var continuationTask = task.ContinueWith(a => WriteToFileTask("bing.htm", a.Result));
The DownloadBytes extension method on the WebClient returns a Task which has already started, we then specify a continuation to execute "after" the Task completes by calling the "ContinueWith" method on the Task instance which in this case is itself a Task which works on the result of the antecedent task (a byte) obtained by calling the "WriteToFileTask" method which is responsible for writing out the byte to a file.
It's important to note that we have to wait for the "continuation" to complete by calling continuationTask.Wait(), otherwise the process will terminate since we are running on a console app. The same would hold true in case of a Webforms client since the calling Page would continue processing and not wait for the Task to complete.
Notice how the client code seems pretty terse in terms of expressing the intent. One can easily read the code and figure out what's going on.
As always happy coding!