Over a million developers have joined DZone.

Async and RestSharp for Windows Phone 7

· Mobile Zone

Visually compose APIs with easy-to-use tooling. Learn how IBM API Connect provides near-universal access to data and services both on-premises and in the cloud, brought to you in partnership with IBM.

I have mentioned RestSharp quite a lot of times, it is simply an essential library for building applications that communicate to the outside world. Ever since Async CTP shipped for Windows Phone 7, I wanted to make everything asynchronous. RestSharp comes with asynchronous methods already built in, but they are not compatible with Async since they don’t return Task.

But we can fix that easily with our good friend TaskCompletionSource<T>

The idea is simple: create a TaskCompletionSource instance which will capture our asynchronous task and use regular ExecuteAsync method. Once it completes, it will transition the task to either Faulted state by setting the exception or to Completed state by setting the result.

Let’s convert ExecuteAsync method first:

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;
}

Looks good enough, what about generic method ExecuteAsync<T> that deserializes the content? Here we have a dilemma: what should the return type be? I have decided to return deserialized instance of type T i.e. theresponse.Data property directly instead of the full response, but you can change the code easily if you want to return the response instead. Here is the snippet:

public static Task<T> ExecuteTaskAsync<T>(this RestClient @this, RestRequest request)
    where T : new()
{
    if (@this == null)
        throw new NullReferenceException();

    var tcs = new TaskCompletionSource<T>();

    @this.ExecuteAsync<T>(request, (response) =>
    {
        if (response.ErrorException != null)
            tcs.TrySetException(response.ErrorException);
        else
            tcs.TrySetResult(response.Data);
    });

    return tcs.Task;
}

You can now use await method with RestSharp libraries. Happy coding.


The Mobile Zone is brought to you in partnership with Strongloop and IBM.  Visually compose APIs with easy-to-use tooling. Learn how IBM API Connect provides near-universal access to data and services both on-premises and in the cloud.

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}