1

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.

NibblyPig
  • 51,118
  • 72
  • 200
  • 356
Alen Alex
  • 897
  • 4
  • 15
  • 31

1 Answers1

-1

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`
    }  

 }
}
HariHaran
  • 3,642
  • 2
  • 16
  • 33
  • Thanks HariHaran for the response. But, it seems Dispose doesn't exactly do the cleanup in case of `HttpClient`, as can be understood from this document: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ – Alen Alex Nov 20 '19 at 10:21
  • @AlenAlex read it again. The solution is to use `static` client. Which i have already used in the answer. Try it on your code – HariHaran Nov 20 '19 at 10:31