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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Beyond Manual Annotation: Engineering Self-Correcting Pseudo-Labeling Pipelines
  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  • Implementing Secure API Gateways for Microservices Architecture
  • Contract-First Integration: Building Scalable Systems With Flyway, OpenAPI, and Kafka

Trending

  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  • 5 AI Security Incidents That Broke Things in Production (and What They Have in Common)
  • Why Stable RAG Answers Can Still Hide Unstable Evidence
  • Alternative Structured Concurrency
  1. DZone
  2. Data Engineering
  3. Databases
  4. Wrapping Begin/End Async API Into C#5 Tasks

Wrapping Begin/End Async API Into C#5 Tasks

By 
Toni Petrina user avatar
Toni Petrina
·
Apr. 02, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
11.2K 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

Opinions expressed by DZone contributors are their own.

Related

  • Beyond Manual Annotation: Engineering Self-Correcting Pseudo-Labeling Pipelines
  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  • Implementing Secure API Gateways for Microservices Architecture
  • Contract-First Integration: Building Scalable Systems With Flyway, OpenAPI, and Kafka

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook