0

I use the rule of thumb to always put inside a using statement everything that implements IDisposable. But I'm starting to work with Tasks and I can't add a using statement like this:

var getResultTasks = new List<Task<HttpResponseMessage>>();

getResultTasks.Add(_client.GetAsync(requestUri));
getResultTasks.Add(_client.GetAsync(requestUri));

using var httpGetResponseMessages = await Task.WhenAll(getResultTasks);

It says:

'HttpResponseMessage[]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.

I can apply it without problems to a single instance though:

using var testing = await _client.GetAsync("");
user33276346
  • 1,501
  • 1
  • 19
  • 38
  • You could take a look at this: [Do I need to dispose of Tasks?](https://devblogs.microsoft.com/pfxteam/do-i-need-to-dispose-of-tasks/) Spoiler alert: *“No. Don’t bother disposing of your tasks.”* – Theodor Zoulias Feb 11 '21 at 01:46
  • Related: [Make using statement usable for multiple disposable objects](https://stackoverflow.com/questions/56309952/make-using-statement-usable-for-multiple-disposable-objects) (one of my own first questions in this site) – Theodor Zoulias Feb 11 '21 at 02:20

1 Answers1

1

Since .net core 3, calling Dispose on a http HttpResponseMessage may not always be needed.

In short, In the majority of cases the body of the response from the underlying connection Socket is fully received, and the byte data representing the content will be buffered into a MemoryStream automatically. This occurs when using most overloads of the HttpClient APIs (GetAsync, PostAsync and SendAsync).

Calling dispose will only dispose the underlying MemoryStream which is not needed. However, there are cases where this is not true, so if you do not completely understand what is going on, call Dispose on a HttpResponseMessage. In your case you have a list of HttpResponseMessage, then just loop through the list manually

var responses = await Task.WhenAll(getResultTasks);

foreach(var response in response)
{
   // do something with the result maybe

   response?.Dispose();

   // job done
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • I read that a foreach disposes automatically (link at the end). By the way, isn't it possible to use the using operator somehow so the IDisposable is automatically disposed https://csharpindepth.com/articles/IteratorBlockImplementation#:~:text=The%20foreach%20statement%20in%20C%23,sure%20that%20Dispose%20is%20called. – user33276346 Feb 11 '21 at 12:11