I'm currently working with ASP.NET core 3.1 and C# 8.
This is the very first time that I'm touching on the whole IAsyncDisposable
story, so it is entirely possible that my understanding is only partial and that this question is a dumb one.
Based on my understanding a type should implement the IAsyncDisposable
interface when it needs to release the resources that it owns in an asyncronous way, so that the required disposal can be carried on without blocking a thread. Put another way, IAsyncDisposable
is the asyncronous counterpart of IDisposable
which allows to release class resources in an efficient manner (in terms of threads usage).
The language supports the consumption of types implementing the IAsyncDisposable
by means of the new await using
construct, which is basically the asyncronous counterpart of the using
keyword.
So far so good.
I have noticed that there are some BCL types which implements both IAsyncDisposable
and IDisposable
, one of them being the Stream
abstract class. I have encountered this scenario while working on uploaded files in ASP.NET core and calling the IFormFile.OpenReadStream
method.
My question now is the following: how should I consume a type implementing both IAsyncDisposable
and IDisposable
? Should I use the classic using
keyword or should I opt for await using
?
The piece of code I was writing is a syncronous one, so the most natural way to deal with the stream is the following:
using var readStream = uploadedFile.OpenReadStream();
var options = new LoadOptions(loadFormat);
return new Workbook(readStream, options);
Should I make my method async
in order to being able to use await using
in the following manner ?
await using var readStream = uploadedFile.OpenReadStream();
var options = new LoadOptions(loadFormat);
return new Workbook(readStream, options);
(consider that, apart the await using
call, my method does not need to be asyncronous)
What is the difference in calling Dispose
versus DisposeAsync
for a type implementing both of them ?