33

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

1
  • 2
    Putting the for loop within the using statement will allow for the reuse of the client though not static for the life time of the main method. Commented Oct 22, 2016 at 1:00

2 Answers 2

37

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.

Sign up to request clarification or add additional context in comments.

6 Comments

It also consumes finite socket resources every time you make one. See codereview.stackexchange.com/questions/69950/…
well yes that's what the article is saying but i am asking what's the difference between putting the for loop inside the using statement versus that of the given code
In that specific case? None at all, since the lifetime of the static object is no different from the lifetime of the Main() method of that application. In the case where you're doing an event-driven program like WinForms, WPF, etc., a public static field/property is a decent way to share this across the entire life of your program.
i am about to post that code thank you for saving me the time yes that is what i am talking about
my bad i didn't notice the declaration of the static variable above
|
23

Adding an answer to reference Microsoft's docs:

https://learn.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.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.