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.

1namespace RestSharpEx
2{
3 public static class RestClientExtensions
4 {
5 public static Task<IRestResponse> ExecuteTaskAsync(this RestClient @this, RestRequest request)
6 {
7 if (@this == null)
8 throw new NullReferenceException();
9
10 var tcs = new TaskCompletionSource<IRestResponse>();
11
12 @this.ExecuteAsync(request, (response) =>
13 {
14 if (response.ErrorException != null)
15 tcs.TrySetException(response.ErrorException);
16 else
17 tcs.TrySetResult(response);
18 });
19
20 return tcs.Task;
21 }
22 }
23}

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

1var client = new RestClient("http://www.YOUR SITE.com/api/");
2var request = new RestRequest("Products", Method.GET);
3var response = await client.ExecuteTaskAsync(request);