Skip to content

@laurentkempe /RestClientExtensions.cs
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.