skip to content

A C# desktop app's memory grows with every document window closed, and each window subscribed to a long-lived settings service's Changed event; why, and how do you fix it?

level: seniorimportance: must knowfreq 60%

answer

  1. who still references the closed window
  2. a path from a root
  3. the service's event field
  4. -= at the end of the window's life

basics

~20 s

Each closed window is still reachable: the settings service's Changed field holds a delegate whose Target is the window. Fix it by unsubscribing with an equal delegate when the window closes, typically in Dispose, and making sure Dispose is called.

solid answer

~40 s

Closing a window does not make it unreachable. The settings service lives for the whole app, its `Changed` field holds a multicast delegate, and each entry's `Target` is a window, or a closure that captured one, so every window ever opened, with its controls and document, survives every collection. To confirm it, ask which reference holds a closed window: the path to a root runs through the service's event field. The fix is to remove the handler when the window's life ends, in `Dispose` or the close handler, with an equal delegate (a method group or the stored lambda instance), and to make sure whoever owns the window actually disposes it. Calling `Dispose` alone frees nothing; the `-=` is what cuts the reference.

code

csharp · 32 lines
csharp
using System.Runtime.CompilerServices;

var settings = new SettingsService();                 // lives as long as the app
var leaked = OpenAndClose(settings, unsubscribe: false);
var clean = OpenAndClose(settings, unsubscribe: true);
GC.Collect();
Console.WriteLine($"closed without -=: alive = {leaked.TryGetTarget(out _)}");  // True
Console.WriteLine($"closed with -=:    alive = {clean.TryGetTarget(out _)}");   // False
Console.WriteLine($"handlers on settings: {settings.HandlerCount}");             // 1

[MethodImpl(MethodImplOptions.NoInlining)]
static WeakReference<DocumentWindow> OpenAndClose(SettingsService settings, bool unsubscribe)
{
    var window = new DocumentWindow(settings);
    if (unsubscribe) window.Dispose();
    return new WeakReference<DocumentWindow>(window);
}

sealed class SettingsService
{
    public event EventHandler? Changed;
    public int HandlerCount => Changed?.GetInvocationList().Length ?? 0;
}

sealed class DocumentWindow : IDisposable
{
    private readonly SettingsService _settings;
    private readonly byte[] _document = new byte[10_000_000];  // what the leak really costs
    public DocumentWindow(SettingsService settings) => (_settings = settings).Changed += OnSettingsChanged;
    private void OnSettingsChanged(object? sender, EventArgs e) => Console.WriteLine(_document.Length);
    public void Dispose() => _settings.Changed -= OnSettingsChanged;
}

go deeper

for a junior

Know that a closed window is not freed while a long-lived service's event still holds its handler, and that -= is what releases it.

for a middle

Explain the reference chain from the service's event field through the delegate's Target to the window, and why Dispose without -= changes nothing.

for a senior

Diagnose from the symptom: ask which reference holds the window, find the event field on the path to root, fix with an equal -= in teardown, and prove it with a WeakReference test.

for a principal

Treat this as a recurring class of defect: decide how subscriptions to app-lifetime services are owned and torn down so that each window does not depend on remembering one line.

## The symptom and what it means Memory that rises by roughly one window's worth each time a window is **closed** points at something that should have become unreachable and did not. In a .NET app, an object is collected only when no chain of references leads to it from a root. A closed window is supposed to have no such chain. If it survives, some object that is still alive refers to it. ## Finding the reference that holds the window The useful question is not "what allocates?" but **"which reference keeps a closed window reachable?"** Walk backwards from the window: 1. the window is the `Target` of an `EventHandler` delegate, or it is captured by a closure that is that delegate's `Target`; 2. that delegate is an entry in a multicast delegate; 3. the multicast delegate is stored in the settings service's event field (for a field-like event, a private field with the same name as the event, here `Changed`); 4. the settings service is held by the application for its whole life. A heap dump's path to root shows exactly this chain; the tooling belongs to the .NET runtime material, but the reasoning is pure C#. Once you see the event field on the path, the cause is settled: the window subscribed and never unsubscribed. ## Why the subscription is invisible in the code The leak usually hides in one innocent line in the window's constructor: ```csharp settings.Changed += OnSettingsChanged; ``` Nothing in the language ties that subscription to the window's lifetime. The event keeps a strong reference until someone calls `-=` with an equal delegate. Closing the window, hiding it, nulling the window's own fields or calling `Dispose` on it does not touch the service's list. | Action on close | Cuts the service → window reference? | |---|---| | Nulling the window's own fields | No: references *out of* the window do not keep it alive | | Calling `Dispose` that does not call `-=` | No: `Dispose` is an ordinary method the collector knows nothing about | | `settings.Changed -= OnSettingsChanged` | **Yes**: an equal delegate is removed from the list | | `settings.Changed -= (s, e) => Refresh()` | No: a new lambda never equals the one added | ## The fix - **Unsubscribe in the window's teardown.** Put `settings.Changed -= OnSettingsChanged;` in `Dispose` (or the framework's close or unload hook), mirroring every `+=` in the constructor. - **Use an equal delegate.** Subscribe with a method group, or store a lambda in a field and remove that field's value. A second inline lambda removes nothing. - **Make sure teardown runs.** The window's owner must dispose it; a `Dispose` nobody calls fixes nothing. How to implement the disposal pattern itself belongs to the material on `IDisposable`. - **Make `-=` safe to repeat.** Removing a handler that is not in the list is a silent no-op, so a `Dispose` called twice does no harm. ## Variants of the same leak - **Static events.** If `Changed` were `static`, the root would be a static field that lives as long as its type is loaded. There is no service instance to retire, so the only cure is `-=`. - **Captured windows in other handlers.** A lambda subscribed to some *other* long-lived event that captures the window, or that captures a local the compiler placed in the same closure object as the window, keeps it alive just as surely. The closure, not the window, is the delegate's `Target`, so search for closures that capture it. - **Handlers that still run.** A leaked window does not just cost memory: its handler keeps running on every raise, refreshing controls that are no longer shown and sometimes throwing because the window has torn down its resources. ## Verifying the fix Hold a `WeakReference<T>` to a window, close and dispose it, force a collection in a test, and check `TryGetTarget`. In the snippet below, the window closed without `-=` stays alive and the one that unsubscribed is collected, and the service's list still carries the leaked window's handler. Two details make such a test trustworthy: - **Create the window in a separate, non-inlined method** that returns only the weak reference. A local variable in the test method, or a variable captured by a lambda in the same scope, can keep the window reachable and make a correct fix look broken. - **Assert on the leaked case too.** A test that only checks the fixed path cannot tell "the fix works" from "the test never observes anything"; showing that the unsubscribed window is collected while a deliberately leaked one is not proves the test can see the difference. The same reasoning applies to every long-lived publisher in the app: anything that lives for the whole session and exposes an event is a candidate root for every short-lived object that subscribes to it.

  • How would you write a regression test that proves a closed window can be collected?
    Create and dispose the window inside a separate non-inlined method that returns only a `WeakReference<T>` to it, so no local in the test keeps it alive. Then call `GC.Collect()` and assert that `TryGetTarget` returns false. If the window is still subscribed to a long-lived event, the assertion fails because the publisher's delegate keeps it reachable.
  • The window does call -= in Dispose, yet it still leaks. What else would you look for?
    Check that the `-=` uses an equal delegate (a method group or the stored instance, not a fresh lambda) and that the owner really calls `Dispose`. Then look for other long-lived publishers the window subscribed to, static events, and lambdas registered elsewhere that capture the window, or a variable sharing one closure object with it, because those closures keep it reachable too.

  • Closing or hiding a window lets the garbage collector reclaim it automatically.
  • Calling Dispose on the window releases it even if the handler is never removed.
  • Setting the window's own fields to null breaks the reference from the service.
  • Unsubscribing in the window's finalizer releases it once the window is collected.
  • Forcing GC.Collect after closing each window fixes the growth.