Home Wraping sync API into Async method
Reply: 2

Wraping sync API into Async method

IntelligentBinary
1#
IntelligentBinary Published in 2014-02-01 08:24:02Z

My MVC application consumes a library and some methods of this library call WCF service internally. All methods exposed from this DLL are sync (none of them return Task or Task) and since we don't own that assembly, it is not possible to convert them into Async API.

However, because these methods call WCF service, they are network bound (so ideally they should be async).

I want to use async controller actions in my MVC application to make it more scalable. My question is how to make the entire method pipeline await able when one method is sync in nature.

Async action --> await async method --> await async method 2 --> sync method from library?

Should I use TaskCompletionSource or Task.FromResult to wrap the library method call?

Also, if I use above approach, will my code more scalable than sync version?

Nair
2#
Nair Reply to 2014-02-01 08:49:28Z

TaskCompletionSource<T> is a way to create a puppet Task, which can complete at any point you like, and can make it fault at any point you like. This means, this would ideal in your case since you have no control over the API method, which you are trying to consume. Following example will give you a head start.

public class HomeController : Controller
 {
    public async Task<ActionResult> Index()
    {
    ViewBag.Message = await ProcessRequest();

    return View();
    }


    //TResult -> can be of any built-in or custom type that you should decide.
    Task<TResult> ProcessRequest()
    {

    // Make a TaskCompletionSource so we can return a puppet Task
    TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>();

    // Call your sync API method
    SyncAPI syncApi = new SyncAPI();

    // Call api method and set the result or exception based on the output from the API //method.
    tcs.SetResult(TResult);

    // Return the puppet Task, which isn't completed yet
    return tcs.Task;
    }
}
Stephen Cleary
3#
Stephen Cleary Reply to 2014-02-01 10:01:04Z

My question is how to make the entire method pipeline await able when one method is sync in nature.

You can't. The only solution is to rewrite the dll.

Should I use TaskCompletionSource or Task.FromResult to wrap the library method call?

Neither.

Also, if I use above approach, will my code more scalable than sync version?

No. It will be slightly less scalable.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.378403 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO