如何在异步/等待中使用 RestSharp [英] How to use RestSharp with async/await

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

问题描述

我正在努力寻找一些异步 C# 代码的现代示例,该代码将 RestSharp 与 asyncawait 结合使用.我知道 Haack 最近更新了 但我不知道如何使用新方法.

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.

此外,我如何提供取消令牌以便可以取消操作(例如,如果一个人厌倦了等待并按下应用 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).

推荐答案

好吧,Haack 所指的更新是我自己做的 :) 所以让我告诉你如何使用它,因为它实际上非常简单.以前,您有像 ExecuteAsyncGet 这样的方法,它会返回一个名为 RestRequestAsyncHandle 的 RestSharp 自定义类型.由于 async/await 适用于 TaskTask 返回类型,因此无法等待此类型.我的拉取请求向返回 Task 实例的现有异步方法添加了重载.这些 Task 重载在其名称中添加了一个任务"字符串,例如 Task 用于 ExecuteAsyncGet 的重载是称为 ExecuteGetTaskAsync.对于每个新的 Task 重载,有一种方法不需要指定 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);

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

这将使用 ExecuteTaskAsync 重载返回一个 Task 实例.当它返回一个 Task 时,你可以在这个方法上使用 await 关键字并返回 Task 的返回类型(在在这种情况下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).

您可以在此处找到代码:http://dotnetfiddle.net/tDtKbL

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

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

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