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).
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.
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 namedRestRequestAsyncHandle
. This type could not be awaited asasync/await
works onTask
andTask<T>
return types. My pull-request added overloads to the existing async methods that returnTask<T>
instances. TheseTask<T>
overloads have an added "Task" string added to their names, for example theTask<T>
overload forExecuteAsyncGet
is calledExecuteGetTaskAsync<T>
. For each of the newTask<T>
overloads there is one method that does not require aCancellationToken
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
:This will use the
ExecuteTaskAsync
overload that returns aTask<IRestResponse>
instance. As it returns aTask
, you can use theawait
keyword on this method and get returned theTask<T>
's returned type (in this caseIRestResponse
).You can find the code here: http://dotnetfiddle.net/tDtKbL