0

I know there are many questions about calling dispose on HttpClient and my understanding is it isn't necessary, but shouldn't (normally) cause any harm in .net core / when using HttpClientFactory. I am wondering about the effect (if any) on 1 particular use case:

HttpResponseMessage response = null;
using (HttpClient client = httpFactory.Create("NEW"))
{
    const string url = "https://url";
    response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead));
}

Stream stream = await response.Content.ReadAsStreamAsync();
...........  use stream .............................

Does disposing the httpclient run the risk of cleaning-up/impacting the HttpResponseMessage/Stream (assume the stream processing take a long time)?

Thanks

  • 1
    What happened when you tried it? – mjwills Aug 22 '21 at 05:39
  • There doesn't seem to be problems when implementing things as above. However, I ran across an older post where someone mentioned they were having intermittent issues (would fail 2 out of 10 times) with accessing a Stream when retrieved via HttpClient. They eventually identifed the issue to be related to disposing the httpclient and trying to access the HttpResponseMessage and accompanying stream after this was done. They were on .Net 4.X vs. .Net Core, and didn't have the option of using HttpClientFactory, so I'm not sure whether the risk of it happenig in .Net Core is still present. – user16723986 Aug 22 '21 at 17:07
  • Any chance you could mention that specific post in your question? – mjwills Aug 22 '21 at 22:06
  • Oh, found it (took a bit of searching): https://stackoverflow.com/questions/40348278/stream-from-response-content-readasstreamasync-is-not-readable-randomly The post mentions "Global.asax.cs", which I took to mean it is on .Net 4.X and not .Net Core, but that could be a wrong assumption. I looked at the Microsoft source code, and I *think* it is ok when using HttpClientFactory, but i am not 100% (the worry is whether the cleanup from the dispose call could be delayed for the httpclientfactory pattern and lead to the prob) and wanted to see if anyone already analyzed this/knows for sure. – user16723986 Aug 23 '21 at 03:54
  • I'll probably just remove the HttpClient using block in the code we have, but I'm still interested to know what actually/can happen for this situation! – user16723986 Aug 23 '21 at 04:01

0 Answers0