Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Wrapping Begin/End Asynchronous API into C#5 Tasks

DZone's Guide to

Wrapping Begin/End Asynchronous API into C#5 Tasks

·
Free Resource

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
                bool flag = tcs.TrySetException(ex);
                if (flag && ex as ThreadAbortException != null)
                {
                    tcs.Task.m_contingentProperties.m_exceptionsHolder.MarkAsHandled(false);
                }
            }
        }, 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)
                {
                    bool flag = tcs.TrySetException(ex);
                    if (flag && ex as ThreadAbortException != null)
                    {
                        tcs.Task.m_contingentProperties.m_exceptionsHolder.MarkAsHandled(false);
                    }
                }
            });
        }
        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.

Topics:

Published at DZone with permission of Toni Petrina, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}