HttpClient in using statement

后端 未结 2 1162
名媛妹妹
名媛妹妹 2020-12-29 06:03

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条回答
  • 2020-12-29 06:07

    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.

    0 讨论(0)
  • 2020-12-29 06:12

    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.

    0 讨论(0)
提交回复
热议问题