For a long time, the ‘using’ statement in C# introduced some convenience when Disposing classes implementing the IDisposable interface.
The following statement:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using(var disposable = new Disposable()) | |
{ | |
} | |
is syntactic sugar for:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
IDisposable disposable = new Disposable(); | |
try | |
{ | |
// Do Something... | |
} | |
finally | |
{ | |
disposable.Dispose(); | |
} |
In C# 8.0 a new System.IAsyncDisposable interface was introduced. This interface enables asynchronous cleanup operations.
To use it you need to use the ‘await using’ statement:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
await using (var disposable = new AsyncDisposable()) | |
{ | |
// Do Something... | |
} |
that is syntactic sugar for:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
IAsyncDisposable disposable = new AsyncDisposable(); | |
try | |
{ | |
// Do Something... | |
} | |
finally | |
{ | |
await disposable.DisposeAsync(); | |
} |