如何使用RestSharp与异步/计谋 [英] How to use RestSharp with async/await

查看:2132
本文介绍了如何使用RestSharp与异步/计谋的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我苦苦寻找的使用RestSharp与异步一些异步C#code和计谋。我知道有由哈克<是一个新的更新/一>,但我不知道如何使用新的方法。

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.

另外,我怎样才能提供一个取消标记使操作可以取消(比方说,如果一个人厌倦了等待和presses取消在应用程序的UI按钮)。

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

推荐答案

那么,更新哈克是指已经由我:)那么让我来告诉你如何使用它,因为它其实很简单。 previously你有一个像 ExecuteAsyncGet 方法,将返回 RestRequestAsyncHandle 名为RestSharp自定义类型。这种类型不能等待为异步/计谋适用于工作任务&LT; T&GT; 返回类型。我拉的请求添加到重载返回任务&LT现有的异步方法; T&GT; 实例。这些任务&LT; T&GT; 重载有一个额外的任务字符串添加到他们的名字,例如任务&LT; T&GT; 重载 ExecuteAsyncGet ExecuteGetTaskAsync&LT; T&GT; 。对于每一个新的任务&LT的; T&GT; 重载有没有需要一个方法的CancellationToken 来指定,还有一个没有。

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.

因此​​,现在到一个实际的例子就如何使用它,这也将展示如何使用的CancellationToken

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

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

这将使用 ExecuteTaskAsync 重载返回任务&LT; IRestResponse&GT; 实例。因为它返回一个工作,您可以使用计谋关键字这种方法并获得返回的任务&LT; T&GT; 的返回类型(在这种情况下, IRestResponse )。

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

您可以在这里找到code: http://dotnetfiddle.net/tDtKbL

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

这篇关于如何使用RestSharp与异步/计谋的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆