For unmanaged or expensive resources (connections, file handles, streams) that must be released immediately, not whenever the GC runs.
1 2 3 4 5 6 7 8 9 10 11 12 13 | // ====================================================================== // Q: IDisposable and using: why and when? // // For unmanaged or expensive resources (connections, file handles, streams) that // must be released immediately, not whenever the GC runs. using calls Dispose // even on an exception. IAsyncDisposable / await using for async cleanup. // Whatever the DI container creates, the container disposes at the end of the // scope. Do not Dispose injected services. Finalizers only if you directly hold // an unmanaged handle (rare; usually SafeHandle). // ====================================================================== await using var stream = File.OpenRead(path); // Dispose at the end of the scope using var activity = ActivitySource.StartActivity("ImportPrices"); |