Stop using using for HttpClient....NO WAIT, USE USING

7/16/2020

Following some advice I read here: YOU'RE USING HTTPCLIENT WRONG..., I switched our website to use static HttpClients for all of our Web API calls. Things worked great through our testing/staging environments. I even originally wrote this article suggesting it. Life was good. And the code went to prod...

Things started breaking in our production environment. Users, managers not happy. Life was not good. The website would lock up and we would have to restart the app pool repeatedly.

Although I was not able to see the errors directly, from what I understood, we had some of these Web API calls returning 404 errors. Since we had a static HttpClients for all Web API calls, ALL users were using this single one. If all the calls were to complete successfully and in a timely manner, there wouldn't have been a problem. However instead, resources were getting locked up, requiring app pool restarts. A hot-fix (and some explaining to management) was in order.

So...instead of trying to use a static HttpClients for all calls, use it like it was intended, using a local instance, wrapped in a using:

 
public static async Task MakeARESTCall(string url)
{
    using (var client = new HttpClient())
    {
        var result = await client.GetAsync(url);
        ...
    }
}

Please register or login to add a comment.

Comments (displaying 1 - 1):
No comments yet! Be the first...


  • C#/.NET
  • T-SQL
  • HTML/CSS
  • JavaScript/jQuery
  • .NET 8
  • ASP.NET/MVC
  • Xamarin/MAUI
  • WPF
  • Windows 11
  • SQL Server 20xx
  • Android
  • XBox
  • Arduino
  • Skiing
  • Rock Climbing
  • White water kayaking
  • Road Biking