SkillPilotAI

Memory, GC, IDisposable and Span

The garbage collector frees managed memory on its own schedule, but files, connections and other OS resources must be released by you with IDisposable and using. On hot paths, Span and Memory cut allocations, and BenchmarkDotNet tells you whether an optimization really helps.

28.1 Why is it used?

  • A StreamWriter takes a file handle from the OS; the file stays locked until that handle is closed.
  • The GC only cleans up memory, and only when it decides to, so nobody knows when the handle would be freed.
  • IDisposable + using closes a resource right now, deterministically.
  • Unneeded allocations (like Substring on every parse) add GC pressure on busy paths.

28.2 The bug: the file was never closed

C#
var writer = File.CreateText("orders.log");writer.WriteLine("Order 1042 paid via UPI"); File.Move("orders.log", "orders-old.log");Console.WriteLine("Log rotated");
Output
$ dotnet run Leak.csUnhandled exception. System.IO.IOException:  The process cannot access the file because  it is being used by another process.   at Program.<Main>$(String[] args)   in Leak.cs:line 4

The "other process" is our own program, still holding the handle.

28.3 GC generations: 0, 1, 2

C#
var order = new byte[1_000];Console.WriteLine(GC.GetGeneration(order)); GC.Collect();Console.WriteLine(GC.GetGeneration(order)); GC.Collect();Console.WriteLine(GC.GetGeneration(order)); var bigImage = new byte[100_000];Console.WriteLine(GC.GetGeneration(bigImage));
Output
$ dotnet run Gen.cs0122
  • Every new object starts in Gen 0; surviving a collection promotes it to Gen 1, then Gen 2.
  • Objects bigger than 85,000 bytes go straight to the Large Object Heap (LOH), counted as Gen 2.
  • GC.Collect() is used here only for the demo; do not call it in real code.
Generational GC
  1. 1.Gen 0: new objects, fast collections

  2. 2.Most objects die young and are freed in Gen 0

  3. 3.Survivors are promoted to Gen 1

  4. 4.Long-lived objects end up in Gen 2 (full GC is expensive)

  5. 5.Objects over 85 KB go to the LOH (Gen 2)

Most objects die in Gen 0

28.4 Fix: using

C#
using (var writer = File.CreateText("orders.log")){    writer.WriteLine("Order 1042 paid via UPI");} File.Move("orders.log", "orders-old.log");Console.WriteLine("Log rotated");
Output
$ dotnet run Fix.csLog rotated
  • When the block ends, the compiler calls Dispose, which closes the file handle.
  • Dispose runs even if an exception is thrown (using is a try/finally underneath).
using block lifecycle
  1. 1.using (var writer = File.CreateText(...)) opens the file handle

  2. 2.writer.WriteLine(...) inside the block

  3. 3.Block ends (normally or by exception): finally calls writer.Dispose()

  4. 4.File handle closed, lock released

  5. 5.File.Move succeeds: Log rotated

28.5 Your own class: IDisposable

  • A class that owns something disposable should implement IDisposable itself.
  • A disposed flag makes a second Dispose call harmless.
  • For a sealed class this simple version is enough; the full Dispose pattern with a finalizer is only for raw unmanaged handles.
C#
sealed class OrderLogger(string path)    : IDisposable{    readonly StreamWriter writer = new(path);    bool disposed;    public void Write(string message)        => writer.WriteLine(message);    public void Dispose()    {        if (disposed) return;        writer.Dispose();        disposed = true;        Console.WriteLine("Logger disposed");    }}
Output
$ dotnet run Logger.csLogger disposedOrder 1042 paid via UPI

28.6 Async code: await using

  • IAsyncDisposable: closing a file or DB connection can be async.
  • await using awaits DisposeAsync at scope end without blocking the thread.
  • A using declaration (no braces) disposes at the end of the enclosing scope, here the method.
C#
await SaveOrderAsync("Order 1043 paid via card");Console.WriteLine(    await File.ReadAllTextAsync("orders.log")); static async Task SaveOrderAsync(string message){    await using var writer =        File.CreateText("orders.log");    await writer.WriteLineAsync(message);}
Output
$ dotnet run AwaitUsing.csOrder 1043 paid via card

28.7 Span: a slice without a copy

  • Substring creates a new string every time.
  • AsSpan is a window over the same characters: no memory copied; int.Parse accepts a span directly.
C#
string line = "ORD-1042,2499,UPI";Measure("Substring",    () => int.Parse(line.Substring(9, 4)));Measure("Span",    () => int.Parse(line.AsSpan(9, 4))); static void Measure(string name, Func<int> parse){    parse(); // warm-up    long before = GC.GetTotalAllocatedBytes(true);    parse();    long bytes =        GC.GetTotalAllocatedBytes(true) - before;    Console.WriteLine($"{name}: {bytes} bytes");}
Output
$ dotnet run SpanParse.csSubstring: 32 bytesSpan: 0 bytes

28.8 Measure with BenchmarkDotNet

C#
using BenchmarkDotNet.Attributes;using BenchmarkDotNet.Running;BenchmarkRunner.Run<ParseBench>(); [MemoryDiagnoser, ShortRunJob]public class ParseBench{    private string line = "ORD-1042,2499,UPI";    [Benchmark(Baseline = true)]    public int WithSubstring()        => int.Parse(line.Substring(9, 4));    [Benchmark]    public int WithSpan()        => int.Parse(line.AsSpan(9, 4));}
Output
$ dotnet run -c Release| Method        | Mean     | Ratio | Allocated ||-------------- |---------:|------:|----------:|| WithSubstring | 49.83 ns |  1.00 |      32 B || WithSpan      | 36.94 ns |  0.74 |         - |
  • MemoryDiagnoser shows allocations; ShortRunJob does a quick run; each method runs many times for an average.
  • Always run in Release. Absolute numbers differ per machine; look at the ratio and allocations.

28.9 Span vs Memory

C#
await PrintOrderIdAsync("ORD-1042,2499,UPI"); static async Task PrintOrderIdAsync(string line){    ReadOnlySpan<char> id = line.AsSpan(0, 8);    await Task.Delay(100);    Console.WriteLine(id.ToString());}
Output
$ dotnet run SpanAsync.csSpanAsync.cs(7,23): error CS4007: Instance of  type 'System.ReadOnlySpan<char>' cannot be  preserved across 'await' or 'yield' boundary.The build failed. Fix the build errors and run again.
C#
static async Task PrintOrderIdAsync(string line){    ReadOnlyMemory<char> id = line.AsMemory(0, 8);    await Task.Delay(100);    Console.WriteLine(id.Span.ToString());}
Output
$ dotnet run MemoryAsync.csORD-1042
PointSpan<T>Memory<T>
Kindref struct (stack only)Normal struct
Across await / yieldNo (CS4007)Yes
Class field / heapNoYes
Use forSynchronous hot-path codeAsync code and stored data; use .Span to do the work

28.10 Common mistakes

  • A using declaration (using var writer = ...) in top-level code disposes at the end of the program, so File.Move still gets the IOException.
  • Fix: use a using block when a resource must be released early.
  • Myth: a GC means no leaks. The GC only frees unreachable objects; a growing static list is a leak.
  • Events never unsubscribed and timers never disposed also keep objects alive.
  • Calling GC.Collect yourself; the runtime knows when to collect.

28.11 Rules

  1. Wrap anything IDisposable in using or await using.
  2. A class that owns something disposable is IDisposable too.
  3. Do not call GC.Collect.
  4. On hot paths use Span instead of allocations like Substring.
  5. Measure every optimization with BenchmarkDotNet before keeping it.

28.12 Interview tips

  • Managed memory: generational GC; new objects in Gen 0, survivors promoted to Gen 1 and Gen 2; large objects (85 KB+) on the LOH.
  • Unmanaged resources (files, connections): IDisposable + using / await using; Dispose runs even on exceptions.
  • Span is a stack-only, zero-copy slice; Memory works in async code and fields.
  • Prove performance claims with BenchmarkDotNet (MemoryDiagnoser, Release build).
  • Leaks still happen in .NET: static collections, events, timers.