Search code examples
c#.netasync-awaitgarbage-collectiondispose

Does the await automatically dispose the StreamReader resource in C#?


Does it make sense to use the using pattern in this case? Or does await automatically dispose of this resource?

var payload = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

Solution

  • No, and why would it?

    Look at the whole StreamReader API - it i s not ONLY "ReadToEnd" - and even then, what if your code then RESETS the reader to a different position and reads more?

    It would totally go against the API of a StreamReader to automatically dispose it and actively sabotage it in many use cases.

    Also, it would make an async method behave different form the non-async version.

    Ergo - no, it does make no sense for it to dispose, so it does not.