C# & CLR Internals (50 Qs)•Part 2: Concurrency, Zero-Allocation & Advanced Language Features (11 - 24)
How do IDisposable and IAsyncDisposable work, and what is the standard Dispose(bool) pattern?
senior LevelCode ExampleAsync & Promises
In Simple Words:
The .NET Garbage Collector reclaims managed heap memory, but has no knowledge of unmanaged resources (file handles, database sockets, OS window handles). IDisposable provides deterministic release of unmanaged resources via using blocks.
csharp
public class ResourceHolder : IDisposable, IAsyncDisposable {
private SafeHandle _handle;
private bool _disposed;
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this); // Skips expensive finalizer queue!
}
protected virtual void Dispose(bool disposing) {
if (!_disposed) {
if (disposing) { /* Release managed objects */ }
_handle?.Dispose(); // Release unmanaged OS handle
_disposed = true;
}
}
public async ValueTask DisposeAsync() {
// Release async connections/streams
Dispose(false);
GC.SuppressFinalize(this);
}
}