I've noticed that in some case, Visual Studio recommends to do this
await using var disposable = new Disposable();
// Do something
instead of this
using var disposable = new Disposable();
// Do something
What is the difference between using
and await using
?
How should I decide which one to use?
Classic sync using
Classic using calls the Dispose()
method of an object implementing the IDisposable
interface.
using var disposable = new Disposable();
// Do Something...
Is equivalent to
IDisposable disposable = new Disposable();
try
{
// Do Something...
}
finally
{
disposable.Dispose();
}
New async await using
The new await using calls and await the DisposeAsync()
method of an object implementing the IAsyncDisposable
interface.
await using var disposable = new AsyncDisposable();
// Do Something...
Is equivalent to
IAsyncDisposable disposable = new AsyncDisposable();
try
{
// Do Something...
}
finally
{
await disposable.DisposeAsync();
}
The IAsyncDisposable Interface was added in .NET Core 3.0
and .NET Standard 2.1
.
In .NET, classes that own unmanaged resources usually implement the IDisposable interface to provide a mechanism for releasing unmanaged resources synchronously. However, in some cases they need to provide an asynchronous mechanism for releasing unmanaged resources in addition to (or instead of) the synchronous one. Providing such a mechanism enables the consumer to perform resource-intensive dispose operations without blocking the main thread of a GUI application for a long time.
The IAsyncDisposable.DisposeAsync method of this interface returns a ValueTask that represents the asynchronous dispose operation. Classes that own unmanaged resources implement this method, and the consumer of these classes calls this method on an object when it is no longer needed.