RestSharp with Async Await
RestSharp is an excellent open source project to use in a Windows Phone app if you want make http calls to a json api. However it doesn't have any inbuilt support for the async await syntax. Thankfully with C#'s extensions methods we can add this support in our app.
namespace RestSharpEx
{
public static class RestClientExtensions
{
public static Task<IRestResponse> ExecuteTaskAsync(this RestClient @this, RestRequest request)
{
if (@this == null)
throw new NullReferenceException();
var tcs = new TaskCompletionSource<IRestResponse>();
@this.ExecuteAsync(request, (response) =>
{
if (response.ErrorException != null)
tcs.TrySetException(response.ErrorException);
else
tcs.TrySetResult(response);
});
return tcs.Task;
}
}
}
This will add a new function to the RestSharp client type called ExecutreTaskAsync. Inside the method it will call the ExecuteAsync function as you normally would, but has also implemented returning a Task and setting it's results when its complete.
To use the function would be as follows
var client = new RestClient("http://www.YOUR SITE.com/api/");
var request = new RestRequest("Products", Method.GET);
var response = await client.ExecuteTaskAsync(request);