115

I'm struggling to find a modern example of some asynchronous C# code that uses RestSharp with async and await. I know there's been a recent update by Haack but I don't know how to use the new methods.

Also, how can I provide a cancellation token so that the operation can be canceled (say, if a person is sick of waiting and presses the Cancel button in the app's UI).

Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647

2 Answers2

227

Well, the update Haack is referring to has been made by me :) So let me show you how to use it, as it is actually very simple. Previously you had methods like ExecuteAsyncGet that would return a RestSharp custom type named RestRequestAsyncHandle. This type could not be awaited as async/await works on Task and Task<T> return types. My pull-request added overloads to the existing async methods that return Task<T> instances. These Task<T> overloads have an added "Task" string added to their names, for example the Task<T> overload for ExecuteAsyncGet is called ExecuteGetTaskAsync<T>. For each of the new Task<T> overloads there is one method that does not require a CancellationToken to be specified and there is one that does.

So now on to an actual example on how to use it, which will also show how to use a CancellationToken:

private static async void Main()
{
    var client = new RestClient();
    var request = new RestRequest("http://www.google.com");
    var cancellationTokenSource = new CancellationTokenSource();

    var restResponse = 
        await client.ExecuteTaskAsync(request, cancellationTokenSource.Token);

    // Will output the HTML contents of the requested page
    Console.WriteLine(restResponse.Content); 
}

This will use the ExecuteTaskAsync overload that returns a Task<IRestResponse> instance. As it returns a Task, you can use the await keyword on this method and get returned the Task<T>'s returned type (in this case IRestResponse).

You can find the code here: http://dotnetfiddle.net/tDtKbL

Ryan Lundy
  • 204,559
  • 37
  • 180
  • 211
Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
  • AH! I think I :heart: you!! (And very apt, considering it's Valentines day). This would be VERY nice to add to the RestSharp wiki. Ok, so .. any chance there's a PCL of this, also? Or am I pushing my luck? – Pure.Krome Feb 14 '14 at 12:55
  • I'm not sure if a PCL version of this would work, but I will look into it in the future. And I agree it would be nice to add to the wiki, don't know if I'm allowed to edit it (I'm not a regular maintainer of the library). – Erik Schierboom Feb 14 '14 at 13:08
  • Maybe we can get @Haacked into the convo, maybe on Twitter? – Pure.Krome Feb 14 '14 at 13:34
  • +1. @ErikSchierboom: I have a lot of PCL async experience. You can ping me if you have any questions (or just post on SO). – Stephen Cleary Feb 14 '14 at 14:13
  • @ErikSchierboom Do you know if there is a way to port it to Windows Phone 8? I cannot find the function ExecuteTaskAsync on Windows Phone. – poiuytrez Aug 26 '14 at 10:44
  • @poiuytrez I think it could be ported as Windows Phone 8, but I'm not sure unfortunately. – Erik Schierboom Aug 26 '14 at 11:37
  • I found the solution: http://danielgary.net/awaitable-restsharp-for-windows-phone/ – poiuytrez Aug 26 '14 at 12:47
  • 4
    How can I map to my custom IRestResponse implementation? – jpgrassi Mar 24 '15 at 19:18
  • 3
    Because I last used Restsharp around the same time shoulder pads were en vogue, rotary phones were the norm and we all loved hitting up our fav BBS via our Robotics 14.4k modem. Green tick of answer-approval, I shall. – Pure.Krome Jan 15 '17 at 11:21
  • @jpgrassi It is quite some time, but I was now thinking about the same. It is possible to call it like: `await client.ExecuteTaskAsync(request, cancellationTokenSource.Token)` where `TModel` is class to be mapped from response. – Naomak Oct 03 '17 at 12:49
  • Thanks for sharing. This technique makes RestSharp better that other API management tools. – André Mar 29 '19 at 01:59
  • Thanks! I was trying to figure out how get RestSharp to call asyncly in my async method. They don't make it super clear in their naming methods. ExecuteAsync doesnt act like you think it would. – Justin Nov 12 '19 at 20:50
  • Thanks for sharing, but i m not able to generate the output, so i tried the t.Wait(); then the output came for my console application. Is it correct? – Prince Antony G Aug 12 '20 at 15:12
3

In my case, I had to call Task.Wait() for it to work properly. However, I used the version which does not take CancellationTokenSource as parameter.

private static async void Main()
{
    var client = new RestClient();
    var request = new RestRequest("http://www.google.com");
    Task<IRestResponse> t = client.ExecuteTaskAsync(request);
    t.Wait();
    var restResponse = await t;
    Console.WriteLine(restResponse.Content); // Will output the HTML contents of the requested page
}