Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

c# - How to use RestSharp with async/await

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...