Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient in using statement

Tags:

hi i read this article You're using HttpClient wrong and it is destabilizing your software the article is suggesting these 2

  1. Make your HttpClient static
  2. Do not dispose of or wrap your HttpClient in a using unless you explicitly are looking for a particular behaviour (such as causing your services to fail)

now a newbie on c# like me would just follow it like the code posted on the article here is the original code the he said would make the application fail

using System;
using System.Net.Http;
namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Starting connections");
            for(int i = 0; i<10; i++)
            {
                using(var client = new HttpClient())
                {
                    var result = client.GetAsync("http://aspnetmonsters.com").Result;
                    Console.WriteLine(result.StatusCode);
                }
            }
            Console.WriteLine("Connections done");
        }
    }
}

and to fix it he gave this code:

using System;
using System.Net.Http;
namespace ConsoleApplication
{
    public class Program
    {
        private static HttpClient Client = new HttpClient();
        public static void Main(string[] args)
        {
            Console.WriteLine("Starting connections");
            for(int i = 0; i<10; i++)
            {
                var result = Client.GetAsync("http://aspnetmonsters.com").Result;
                Console.WriteLine(result.StatusCode);
            }
            Console.WriteLine("Connections done");
            Console.ReadLine();
        }
    }
}

now being curious like any newbie i thought of the for loop inside the using statement will the effect be the same as the latter?

thank you

like image 434
angelogogo Avatar asked Oct 22 '16 00:10

angelogogo


People also ask

What is the use of HttpClient?

An HttpClient can be used to send requests and retrieve their responses. An HttpClient is created through a builder . The builder can be used to configure per-client state, like: the preferred protocol version ( HTTP/1.1 or HTTP/2 ), whether to follow redirects, a proxy, an authenticator, etc.

Should I use using for HttpClient C#?

The using statement is a C# nicity for dealing with disposable objects. Once the using block is complete then the disposable object, in this case HttpClient , goes out of scope and is disposed. The dispose method is called and whatever resources are in use are cleaned up. This is a very typical pattern in .

What is wrong with this usage of HttpClient?

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors. Below is an example using HttpClient correctly.

What is HttpClient in Web API?

HttpClient is used to send an HTTP request, using a URL. HttpClient can be used to make Web API requests from the console Application, Winform Application, Web form Application, Windows store Application, etc.


2 Answers

The difference is that in the top loop, you're creating 10 total HttpClient objects, using each once, and then disposing of each, while in the bottom, you're creating just one HttpClient and reusing it.

The point of the article is that it's quite inefficient - and wholly unnecessary - to make a new HttpClient object every time you want to make a web service call. Since HttpClient is not only reusable but thread-safe, the preferred method is to make a single HttpClient and reuse it until your program is done making http connections.

Edit

It sounds like you were asking about why not this:

using System;
using System.Net.Http;
namespace ConsoleApplication
{
    public class Program
    {

        public static void Main(string[] args)
        {
            Console.WriteLine("Starting connections");
            using (var client = new HttpClient())
            {
                for(int i = 0; i<10; i++)
                {
                    var result = Client.GetAsync("http://aspnetmonsters.com").Result;
                    Console.WriteLine(result.StatusCode);
                }
            }
            Console.WriteLine("Connections done");
            Console.ReadLine();
        }
    }
}

In this specific case there's no difference. The important thing is that the HttpClient is reused until every request is done. In most realistic scenarios, having a static property for an HttpClient makes the most sense to accomplish this goal.

The reason they say "don't use using" is that using implies your HttpClient is a local variable within a method, and in most cases that isn't what you want. In this specific case, every http request from the program happens within one method which is called only once, so a variable that is local to that method is fine - you end up with one HttpClient that is reused until all requests have occurred and then is disposed.

like image 72
PMV Avatar answered Sep 22 '22 13:09

PMV


Adding an answer to reference Microsoft's docs:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Especially in server applications, creating a new HttpClient instance for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.

like image 17
Jasen Avatar answered Sep 25 '22 13:09

Jasen