Skip to content

Instantly share code, notes, and snippets.

@laurentkempe
Created April 12, 2012 21:59
Show Gist options
  • Save laurentkempe/2371323 to your computer and use it in GitHub Desktop.
Save laurentkempe/2371323 to your computer and use it in GitHub Desktop.
Couple extensions methods to RestSharp to add Async capabilities
#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