Wednesday, July 31, 2013

Going from Tasks back to IAsyncResult(the Asynchronous Programming Model pattern)

There are lot’s of posts out there talking about how to go from the traditional APM approach(using the typical BeginXXX and EndXXX syntax with IAsyncResult) to the Task based approach. Probably the easiest way is by using the Task.Factory.FromAsync method.

But what if you want to do it the other way around and want to go back from a task to the APM way of working?

In my specific case I wanted to wrap the async version of ExecuteNonQuery that returns a Task<int>:

Task<int> ExecuteNonQueryAsync();

It had to be mapped to an APM implementation with the following signatures:

IAsyncResult BeginExecuteNonQuery(DbCommand command, AsyncCallback callback, object state);
int EndExecuteNonQuery(IAsyncResult asyncResult);

I started by implementing it myself but there a lot of edge cases, so I was happy to find the following extension method :

The implementation of my BeginExecuteNonQuery method became:

And the implementation of my EndExecuteNonQuery method became:

A similar solution could be found on Stephen Cleary’s blog who created a useful Helper library for async task-based programming called Nito AsyncEx.

No comments: