我在 restsharp 客户端中发现了一些性能问题,我正在使用 PerformanceRequest2 函数中的 RestSharp 向一些安静的 API 发送请求,并在 PerformRequest 中使用 WebRequest 使用普通的.net 请求

PerformRequest 的平均响应时间为 75ms,而使用 RestSharp 的 PerformRequest2 为 300ms。这是restsharp的一些限制还是我们使用restsharp的方式做错了

private static void PerformRequest2(string requestData)
{
    var request = JsonConvert.DeserializeObject<ComplexClass>(requestData);
    var client2 = new RestClient("URL");
    var restRequest = new RestRequest();
    restRequest.Method = Method.PUT;
    restRequest.AddHeader("Content-Type", "application/json");
    restRequest.AddHeader("Authorization", string.Format("Bearer {0}", token));

    restRequest.AddJsonBody(request);

    var restResponse2 = client2.Execute(restRequest);
    if (restResponse2.StatusCode != HttpStatusCode.OK)
    {
        throw new Exception("error");
    }
}


private static void PerformRequest(string requestData)
{
    var request = JsonConvert.DeserializeObject<ComplexClass>(requestData);
    var webRequest =
        WebRequest.Create("URL");
    webRequest.ContentType = "application/json";
    webRequest.Method = "PUT";
    webRequest.Headers.Add(HttpRequestHeader.Authorization, string.Format("Bearer {0}", token));
    using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
    {
        streamWriter.Write(JsonConvert.SerializeObject(request));
        streamWriter.Flush();
    }
    var httpResponse = (HttpWebResponse) webRequest.GetResponse();

    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
        if (string.IsNullOrEmpty(result))
        {
            throw new Exception("error");
        }
    }
}

最佳答案

我从以下链接得到了答案:

http://romikoderbynew.com/2012/01/17/slow-httpwebrequest-getresponse/

应用修复后,使用restsharp和httpwebrequest的性能相当

关于c# - 与 WebRequest 相比,RestSharp 的性能问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34889943/

10-11 10:51