Consider the following code taken from the the Microsoft docs:
using FileStream createStream = File.Create(fileName);
// ...write to stream etc..
await createStream.DisposeAsync(); // <- isn't this done automatically because of the using clause in the first line`?
Isn't calling the DisposeAsync()
method superfluous?
using
clause will call Dispose()
method, not DisposeAsync()
. It's not the same since Dispose()
is blocking call and the presence of DisposeAsync
suggests that dispose might be resource intensive and so you don't want to call Dispose
if you can instead call DisposeAsync
.
The code as written will first call DisposeAsync
and then at the end of the scope it will also call Dispose
. We can assume it's harmless because implementing class should have a check that resource was already disposed so second Dispose
should do nothing. However, if you use C#8+, you can use await using
:
await using FileStream createStream = File.Create(fileName);
This is the same as using
but it will call await DisposeAsync()
at the end of the scope, instead of Dispose
. So just like you do now, but automatically (and in finally block). It works with IAsyncDisposable
target (such as FileStream
which inherits from Stream
which implements IAsyncDisposable
).