Wrapping Begin/End asynchronous API into C#5 tasks

Microsoft offered programmers several different ways of dealing with the asynchronous programming since .NET 1.0. The first model was Asynchronous programming model or APM for short. The pattern is implemented with two methods named BeginOperation and EndOperation. .NET 4 introduced new pattern – Task Asynchronous Pattern and with the introduction of .NET 4.5, Microsoft added language support for language integrated asynchronous coding style. You can check the MSDN for more samples and information. I will assume that you are familiar with it and have written code using it.

You can wrap existing APM pattern into TPL pattern using the Task.Factory.FromAsync methods. For example:

public static Task<IEnumerable<T>> ExecuteAsync<T>(this DataServiceQuery<T> query, object state)
{
	return Task.Factory.FromAsync<IEnumerable<T>>(query.BeginExecute, query.EndExecute, state);
}

It is easy to wrap most of the asynchronous functions this way, but some cannot be since the wrapper functions assume that the last two parameters to the BeginOperation are AsyncCallback and object, and there are some versions of asynchronous operations that have different specifications.

Examples:

    1. Extra parameters after the object state parameter:
      IAsyncResult DataServiceContext.BeginExecuteBatch(
                              AsyncCallback callback,
      						object state,
      						params DataServiceRequest[] queries);
    2. Missing the expected object state parameter and different return type:
      ICancelableAsyncResult BeginQuery(AsyncCallback callBack);
      WorkItemCollection EndQuery(ICancelableAsyncResult car);

Short solution for the first example

The short and elegant way for wrapping the first example is to provide the following wrapper:

public static Task<DataServiceResponse> ExecuteBatchAsync(this DataServiceContext context,
                                                            object state,
                                                            params DataServiceRequest[] queries)
{
    if (context == null)
        throw new ArgumentNullException("context");
    return Task.Factory.FromAsync<DataServiceResponse>(
                            context.BeginExecuteBatch(null, state, queries),
                            context.EndExecuteBatch);
}

We simply call the Begin method ourselves and then wrap it using an another overload for FromAsync function.

The longer way

However, we can fully wrap it ourselves by simulating what the FromAsync wrapper does. The complete code is listed below.

public static Task<DataServiceResponse> ExecuteBatchAsync(this DataServiceContext context, object state, params DataServiceRequest[] queries)
{
    // this will be our sentry that will know when our async operation is completed
    var tcs = new TaskCompletionSource<DataServiceResponse>();

    try
    {
        context.BeginExecuteBatch((iar) =>
        {
            try
            {
                var result = context.EndExecuteBatch(iar as ICancelableAsyncResult);
                tcs.TrySetResult(result);
            }
            catch (OperationCanceledException ex)
            {
                // if the inner operation was canceled, this task is cancelled too
                tcs.TrySetCanceled();
            }
            catch (Exception ex)
            {
                // general exception has been set
                tcs.TrySetException(ex);
            }
        }, state, queries);
    }
    catch
    {
        tcs.TrySetResult(default(DataServiceResponse));
        // propagate exceptions to the outside
        throw;
    }

    return tcs.Task;
}

Besides educational benefits, writing the full wrapper code allows us to add cancellation, logging and diagnostic information. Once we understand how to wrap APM pattern, We can now tackle the second problem easily.

Handling the BeginQuery/EndQuery

We will first create our own wrapper function in the spirit of the above code with the notable difference that we use the ICancelableAsyncResult interface instead of the IAsyncResult.

public static class TaskEx<TResult>
{
    public static Task<TResult> FromAsync(Func<AsyncCallback, IAsyncResult> beginMethod, Func<ICancelableAsyncResult, TResult> endMethod)
    {
        if (beginMethod == null)
            throw new ArgumentNullException("beginMethod");
        if (endMethod == null)
            throw new ArgumentNullException("endMethod");

        var tcs = new TaskCompletionSource<TResult>();

        try
        {
            beginMethod((iar) =>
            {
                try
                {
                    var result = endMethod(iar as ICancelableAsyncResult);
                    tcs.TrySetResult(result);
                }
                catch (OperationCanceledException ex)
                {
                    tcs.TrySetCanceled();
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
            });
        }
        catch
        {
            tcs.TrySetResult(default(TResult));
            throw;
        }

        return tcs.Task;
    }
}

The code is pretty self-explanatory and we can go ahead with the wrapping. There are four different operations that are exposed both in synchronous and asynchronous version: Query, LinkQuery, CountOnlyQuery and RegularQuery.

The extension methods are short since we have already created our generic wrapper above:

public static Task<WorkItemCollection> RunQueryAsync(this Query query)
{
    return TaskEx<WorkItemCollection>.FromAsync(query.BeginQuery, query.EndQuery);
}

public static Task<WorkItemLinkInfo[]> RunLinkQueryAsync(this Query query)
{
    return TaskEx<WorkItemLinkInfo[]>.FromAsync(query.BeginLinkQuery, query.EndLinkQuery);
}

public static Task<int> RunCountOnlyQueryAsync(this Query query)
{
    return TaskEx<int>.FromAsync(query.BeginCountOnlyQuery, query.EndCountOnlyQuery);
}

public static Task<int[]> RunRegularQueryAsync(this Query query)
{
    return TaskEx<int[]>.FromAsync(query.BeginRegularQuery, query.EndRegularQuery);
}

That is it for today, you can write your own handy extensions easily for APM functions out there.

Last updated by at .

  • Garrett

    What is going on with this line?

    tcs.Task.m_contingentProperties.m_exceptionsHolder.MarkAsHandled(false);

    It doesn’t compile because these properties aren’t exposed in .Net

    • Louis

      Wondering the exact same question.

      • http://www.tonicodes.net/blog/ Toni Petrina

        This is embarrassing, but it appears to be wrong. I’ll update the post.

        • Louis

          Awesome! It’s funny because your second example is using the exact same methods (tfs querying) I was trying to wrap into a task. Thanks for the quick turnaround. Might be a good idea to update the dzone article.

          • http://www.tonicodes.net/blog/ Toni Petrina

            Maybe I should, thanks for the tip :)
            Can I ask you what are you doing with TFS at the moment?

          • Louis

            I’m the lead developer on Urban Turtle (http://urbanturtle.com). So I’m doing lots! :)

  • BarnyardMan

    Toni, I have tried using the wrapper code you posted here: http://dotnet.dzone.com/articles/visual-studio-11-based-async but I’m having a problem when creating a new oData record. I get a meaningless message ‘An error occurred while processing this request.” I can query, update and delete, but I cannot create. Are you aware of any issues that might be causing this?

    • http://www.tonicodes.net/blog/ Toni Petrina

      Hi,
      Have you tried using regular methods that were wrapped using the wrappers on the link you provided? Because those wrappers merely translate one async pattern into another. So it might be that the async method underneath doesn’t work as expected.