RestSharp DownloadData-异步/等待风格

时间:2018-08-29 17:35:14

标签: c# .net async-await restsharp

我是想在RestSharp(http://restsharp.org)客户端中使用async方法的await / DownloadData版本的人之一,如下所述在Github上的这个问题中:https://github.com/restsharp/RestSharp/issues/1028

最近有人发布了这样的东西,尽管它并不完美:
https://github.com/cfHxqA/RestSharp.RestClientSyncUtil/blob/master/RestClient.Sync.Util.cs

/// <summary>
/// Executes the specified request and downloads the response data
/// </summary>
/// <param name="Client">The IRestClient this method extend</param>
/// <param name="Request">Request to be executed</param>
/// <param name="Callback">Callback function to be executed upon completion providing access to current and maximum length</param>
/// <param name="Content">Callback function to be executed upon completion providing access to received bytes</param>
public static async void DownloadDataAsync(this IRestClient Client, IRestRequest Request, Action<int, long> Callback, Action<byte[]> Content) {
  Request.Method = Method.HEAD;
  IRestResponse Response = Client.Execute(Request);

  Client.ConfigureWebRequest((s) => {
    int BytesProcessed = 0;

    System.IO.Stream RemoteStreamObject = null; ;
    System.Net.WebResponse WebResponseObject = null;

    WebResponseObject = s.GetResponse();
    if (WebResponseObject != null) {
      RemoteStreamObject = WebResponseObject.GetResponseStream();

      byte[] buffer = new byte[1024];
      int BytesRead;

      do {
        BytesRead = RemoteStreamObject.Read(buffer, 0, buffer.Length);
        BytesProcessed += BytesRead;

        if (Callback != null) Callback(BytesProcessed, Response.ContentLength);
      } while (BytesRead > 0);
    } // end statement
  });

  Request.Method = Method.GET;
  var TaskAsync = await Client.ExecuteTaskAsync(Request);
  if (Content != null) Content(TaskAsync.RawBytes);
}

即使它不是十全十美,我还是尝试使用这段代码,结果发现它在流同时进行读写操作时会引发错误。

另一方面,我可以执行以下操作:

public static async Task<byte[]> DownloadDataAsync(this IRestClient restClient, IRestRequest restRequest, int bufferSize = 4096)
{
    var restResponse = await restClient.ExecuteTaskAsync(restRequest);
    return await Task.FromResult(restResponse.RawBytes);
}

但不确定是否会充分利用异步操作,我想知道两种实现中哪一种最适合利用async / await

0 个答案:

没有答案