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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • Unlocking the Benefits of a Private API in AWS API Gateway
  • APIs for Logistics Orchestration: Designing for Compliance, Exceptions, and Edge Cases
  • Building Data Pipelines With Jira API

Trending

  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • AI, ML, and Data Science: Shaping the Future of Automation
  • Rethinking Recruitment: A Journey Through Hiring Practices
  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

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

Related

  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • Unlocking the Benefits of a Private API in AWS API Gateway
  • APIs for Logistics Orchestration: Designing for Compliance, Exceptions, and Edge Cases
  • Building Data Pipelines With Jira API

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!