I'm using a .NET library which uses a pre-async/await type of asynchronicity. That is, it provides asynchronous (non-awaitable) method with a callback parameter.
I'm trying to write awaitable extension methods which will wrap some of those methods to make it easier to use with the async/await fashion but I'm not sure if this is the right approach.
Here's an example of one of those methods:
public void OAuthGetRequestTokenAsync(string callbackUrl, Action<FlickrResult<OAuthRequestToken>> callback)
{
CheckApiKey();
string url = //...
Dictionary<string, string> parameters = OAuthGetBasicParameters();
// [Code to add parameters]
FlickrResponder.GetDataResponseAsync(this, url, parameters, (r) =>
{
var result = new FlickrResult<OAuthRequestToken>();
if (r.Error != null)
{
if (r.Error is System.Net.WebException)
{
var ex = new OAuthException(r.Error);
result.Error = ex;
}
else
{
result.Error = r.Error;
}
callback(result);
return;
}
result.Result = FlickrNet.OAuthRequestToken.ParseResponse(r.Result);
callback(result);
});
}
And here's what I came up with to provide an awaitable extension method which wraps the one above:
static class FlickrExtensions
{
public static Task<OAuthRequestToken> OAuthGetRequestTokenAsync(this Flickr flickr,
string callbackUrl)
{
var tcs = new TaskCompletionSource<OAuthRequestToken>();
flickr.OAuthGetRequestTokenAsync(callbackUrl, r =>
{
if (r.HasError)
tcs.TrySetException(r.Error);
else
tcs.TrySetResult(r.Result);
});
return tcs.Task;
}
// More extension methods to be added.
}
Are there any problems with my code or any downsides to this implementation?
Also, is there a better (more standard?) way to achieve this goal?