DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Databases
  4. Wrapping Begin/End Asynchronous API into C#5 Tasks

Wrapping Begin/End Asynchronous API into C#5 Tasks

Toni Petrina user avatar by
Toni Petrina
·
Jun. 21, 12 · Interview
Like (0)
Save
Tweet
Share
9.39K Views

Join the DZone community and get the full member experience.

Join For Free

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.

API

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The 5 Books You Absolutely Must Read as an Engineering Manager
  • Multi-Cloud Integration
  • Create a REST API in C# Using ChatGPT
  • Required Knowledge To Pass AWS Certified Solutions Architect — Professional Exam

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: