DelegatingHandler and HttpClient in a loop

545 Views Asked by At

I am trying to execute HttpClient.GetAsync in a loop.
As per Microsoft Doc, it is recommended to use 1 instance of HttpClient.

The way I'm getting HttpClient is

var httpClient = HttpClientFactory.Create(HttpClientRequestHandler.HttpMessageHandler, delegatingHandler);

It hits GetAsync function fine, the first time, but when I reuse the httpClient reference, I'm getting the error: The 'DelegatingHandler' list is invalid because the property 'InnerHandler' of 'HttpClientTelemetryHandler' is not null.

When I tried creating a new Handler and HttpClient instance in the loop everytime, it works fine.

This is now a conflict of interest. Should I create a new instance everytime in the loop, or is there any other way of doing this which is the right way to do it.

Additional info: The custom library which I consume to create the HttpClient is .Net Standard 2.0 and the client application which calls the HttpClient is .Net Core 2.1.

Appreciate any help.

Thanks.

1

There are 1 best solutions below

2
On BEST ANSWER

Usually this error happens when you reuse the same Handler instance in a batch or a loop.

Disposing the HttpClient properly at the end of each request prevents this error.

public class Test{
 private static HttpClient _httpClient;

 SomeFunction(){
 using (var client = new HttpClient(
       HttpClientFactory.CreatePipeline(
       new HttpClientHandler
           {
              CookieContainer = new CookieContainer(),
              UseCookies = true
            },
       new DelegatingHandler[] { new CustomHandler() })))
    {
         //do something with `client`
    }  

 }
}