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);
Advertisements

One thought on “RestSharp with Async Await

  1. Leopoldo Wagner says:

    Hi,

    Thanks a lot for the Extension.
    I have extendet it a little bit with generic type parameter, So I can use response.Data directly:

    namespace RestSharpEx
    {
    public static class RestClientExtensions
    {
    public static Task<IRestResponse> ExecuteTaskAsync(this RestClient @this, RestRequest request) where T : new()
    {
    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;
    }
    }
    }

    uses Like:

    var response = await Client.ExecuteTaskAsync(Request);
    var MyObject = (MyClass)response.Data;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s