What is the overhead of creating a new HttpClient per call in a WebAPI client?

前端 未结 7 2029
心在旅途
心在旅途 2020-11-22 07:26

What should be the HttpClient lifetime of a WebAPI client?
Is it better to have one instance of the HttpClient for multiple calls?

Wh

7条回答
  •  面向向阳花
    2020-11-22 07:27

    As the other answers state, HttpClient is meant for reuse. However, reusing a single HttpClient instance across a multi-threaded application means you can't change the values of its stateful properties, like BaseAddress and DefaultRequestHeaders (so you can only use them if they are constant across your application).

    One approach for getting around this limitation is wrapping HttpClient with a class that duplicates all the HttpClient methods you need (GetAsync, PostAsync etc) and delegates them to a singleton HttpClient. However that's pretty tedious (you will need to wrap the extension methods too), and fortunately there is another way - keep creating new HttpClient instances, but reuse the underlying HttpClientHandler. Just make sure you don't dispose the handler:

    HttpClientHandler _sharedHandler = new HttpClientHandler(); //never dispose this
    HttpClient GetClient(string token)
    {
        //client code can dispose these HttpClient instances
        return new HttpClient(_sharedHandler, disposeHandler: false)         
        {
           DefaultRequestHeaders = 
           {
                Authorization = new AuthenticationHeaderValue("Bearer", token) 
           } 
        };
    }
    

提交回复
热议问题