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 RestSharpEx2{3 public static class RestClientExtensions4 {5 public static Task<IRestResponse> ExecuteTaskAsync(this RestClient @this, RestRequest request)6 {7 if (@this == null)8 throw new NullReferenceException();910 var tcs = new TaskCompletionSource<IRestResponse>();1112 @this.ExecuteAsync(request, (response) =>13 {14 if (response.ErrorException != null)15 tcs.TrySetException(response.ErrorException);16 else17 tcs.TrySetResult(response);18 });1920 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);