Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Async and RestSharp for Windows Phone 7

DZone's Guide to

Async and RestSharp for Windows Phone 7

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

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.


Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}