Created
April 12, 2012 21:59
-
-
Save laurentkempe/2371323 to your computer and use it in GitHub Desktop.
Couple extensions methods to RestSharp to add Async capabilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#region using | |
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using RestSharp; | |
#endregion | |
namespace TeamCitySharper | |
{ | |
public static class RestClientExtensions | |
{ | |
public static Task<TResult> GetAsync<TResult>(this RestClient client, | |
RestRequest request) where TResult : new() | |
{ | |
var tcs = new TaskCompletionSource<TResult>(); | |
WaitCallback | |
asyncWork = _ => | |
{ | |
try | |
{ | |
client.ExecuteAsync<TResult>(request, | |
response => tcs.SetResult(response.Data)); | |
} | |
catch (Exception exc) | |
{ | |
tcs.SetException(exc); | |
} | |
}; | |
return GetAsync(asyncWork, tcs); | |
} | |
public static Task<TResult> GetAsync<T, TResult>(this RestClient client, | |
RestRequest request, | |
Func<T, TResult> adapter) where T : new() | |
{ | |
var tcs = new TaskCompletionSource<TResult>(); | |
WaitCallback | |
asyncWork = _ => | |
{ | |
try | |
{ | |
client.ExecuteAsync<T>(request, | |
response => | |
tcs.SetResult(adapter.Invoke(response.Data))); | |
} | |
catch (Exception exc) | |
{ | |
tcs.SetException(exc); | |
} | |
}; | |
return GetAsync(asyncWork, tcs); | |
} | |
private static Task<TResult> GetAsync<TResult>(WaitCallback asyncWork, | |
TaskCompletionSource<TResult> tcs) | |
{ | |
ThreadPool.QueueUserWorkItem(asyncWork); | |
return tcs.Task; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment