Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET HttpClient hangs after several requests (unless Fiddler is active)

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

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.

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.

Many thanks,

Tim

like image 776
Tim Coulter Avatar asked Dec 30 '12 22:12

Tim Coulter


1 Answers

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;
    }
}
like image 68
Andrew Arnott Avatar answered Nov 17 '22 20:11

Andrew Arnott