.NET HttpClient在多个请求后挂起(除非Fiddler处于活动状态) [英] .NET HttpClient hangs after several requests (unless Fiddler is active)

查看:104
本文介绍了.NET HttpClient在多个请求后挂起(除非Fiddler处于活动状态)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 System.Net.Http.HttpClient 将来自控制台应用程序的一系列请求发布到REST API,并将JSON响应反序列化为强类型对象。我的实现是这样的:

I am using System.Net.Http.HttpClient to post a sequence of requests from a console application to a REST API and to deserialize the JSON responses into strongly-typed objects. My implementation is like this:

using (var client = new HttpClient())
{
    var content = new StringContent(data, Encoding.UTF8, "text/html");
    var response = client.PostAsync(url, content).Result;

    response.EnsureSuccessStatusCode();

    return response.Content.ReadAsAsync<MyClass>().Result;
}

但是,我遇到的问题与此问题,当通过Fiddler路由请求时,一切正常,但是在禁用Fiddler时,它在第4或第5个请求之后挂起。

However, I am experiencing a problem very similar to one described in this question, whereby everything works fine when the requests are routed via Fiddler, but it hangs after the 4th or 5th request when Fiddler is disabled.

如果问题的原因相同,我认为我需要对 HttpClient 做更多的事情在每次请求后完全释放其资源,但我找不到任何代码示例来演示如何执行此操作。

If the cause of the problem is the same, I assume I need to do something more with HttpClient to get it to fully release its resources after each request but I am unable to find any code samples that show how to do this.

希望有人可以指出正确的方向。

Hoping somebody can point me in the right direction.

非常感谢,

Tim

推荐答案

您不会处理 HttpResponseMessage 对象。这可能会留下服务器开放的流,并且在填充了单个服务器的流配额后,将不再发送任何请求。

You are not disposing of the HttpResponseMessage object. This can leave open streams with the server, and after some quota of streams with an individual server is filled, no more requests will be sent.

using (var client = new HttpClient())
{
    var content = new StringContent(data, Encoding.UTF8, "text/html");
    using(var response = client.PostAsync(url, content).Result)
    {    
        response.EnsureSuccessStatusCode();
        return response.Content.ReadAsAsync<MyClass>().Result;
    }
}

这篇关于.NET HttpClient在多个请求后挂起(除非Fiddler处于活动状态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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