I want to use TPL with a existing API, RestSharp to be specific, so I can use continuations.
But this means I have to wrap a API that doesn’t take the classical .NET approach to async, but instead implements callbacks. Take some code like this:
var client = new RestClient("service-url");
var request = new RestRequest();
client.ExecuteAsync<List<LiveTileWeatherResponse>>(request,
(response) =>
{
...
});
So here I want to wrap the ExecuteAsync in TPL, if it’s possible. But I can’t for the life of me, figure out how to do it.
Any ideas?
TPL provides TaskCompletionSource class which allows you to expose pretty much anything as a Task. By calling SetResult or SetException, you can cause the task to succeed or fail. In your example, you could probably do something like:
You can then use it:
Or, if you want to chain tasks:
You can read more about TaskCompletionSource at http://blogs.msdn.com/b/pfxteam/archive/2009/06/02/9685804.aspx