Unsubscribing and leaks

An event handler is a delegate, and a delegate holds its target. When a long-lived object subscribes a method of a form, the object holds the form, and the form cannot be collected while the object lives. That is the leak this lesson is about, and it is the one a desktop application has most often: the form closes, the user opens it again, and the old one is still there because a model, a timer or a static event still knows its handler.

Who holds whom

The direction is easy to get backwards. model.Changed += form.OnModelChanged stores a delegate in the model's event field; the delegate's Target is the form. So the model now references the form, and the form references the model: neither can be collected by reference counting, and the garbage collector will not collect an object that is still reachable from a live root. A model that lives as long as the application is a root.

using System; using System.Drawing; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new Form1()); } } internal sealed class Form1 : Form { private readonly NotesModel _model = new(); public Form1() { Text = "A form that listens"; ClientSize = new Size(360, 120); _model.Changed += OnModelChanged; FormClosed += (sender, e) => _model.Changed -= OnModelChanged; Controls.Add(new Label { Text = "The model notifies this form.", AutoSize = true, Location = new Point(16, 20), }); } private void OnModelChanged(object? sender, EventArgs e) { Text = "The model changed"; } } internal sealed class NotesModel { public event EventHandler? Changed; public void Clear() { Changed?.Invoke(this, EventArgs.Empty); } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run, and the important line is the one with -= in it: FormClosed += (sender, e) => _model.Changed -= OnModelChanged; hands the handler back when the form closes, the delegate is gone, and the model no longer references the form. The model itself is a field of the form, so on this page the leak is closing: the form owns the model. The leak needs a model that outlives the form, which is the case a dependency passed in from outside creates.

A shorter form of the same idea is to unsubscribe in the Dispose of the form, which the designer already overrides in Form1.Designer.cs. FormClosed is the better place when the form subscribes to something that outlives it, because it runs before the form is disposed and it runs for a form that is closed by the user rather than by the application.

The leaks a form has

The symptom is not a crash. The application's memory grows with every opening of the window, the old forms still react to events, and a diagnostic tool shows several instances of a form the user believes is closed. That is why the rule is worth learning before the symptom: every += on an object that outlives the form needs a -= somewhere.

The unsubscribe

Three details decide whether the -= works:

using System; using System.Windows.Forms; internal sealed class Form1 : Form { private readonly Timer _timer = new() { Interval = 1000 }; private EventHandler? _handler; public Form1() { _handler = (sender, e) => Text = DateTime.Now.ToString("HH:mm:ss"); _timer.Tick += _handler; _timer.Start(); FormClosed += (sender, e) => { _timer.Stop(); _timer.Tick -= _handler; _timer.Dispose(); _handler = null; }; } }

That block is a fragment: a form with no Main, so the checker counts it and does not build it. It keeps the lambda in a field so that it can be removed, and it stops the timer before it disposes it, because a disposed timer that is still enabled raises ObjectDisposedException from its own thread when it next ticks.

The proof that runs

Whether an object is still reachable is a question the runtime answers, and WeakReference is how a program asks it. This program subscribes a subscriber, removes it and collects, and it runs here:

using System; var publisher = new Publisher(); var weak = Subscribe(publisher); Console.WriteLine($"subscribed, alive: {weak.IsAlive}"); publisher.Raise(); publisher.UnsubscribeAll(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Console.WriteLine($"unsubscribed, alive: {weak.IsAlive}"); static WeakReference Subscribe(Publisher publisher) { var subscriber = new Subscriber(); publisher.Changed += subscriber.OnChanged; return new WeakReference(subscriber); } internal sealed class Publisher { public event EventHandler? Changed; public void Raise() => Changed?.Invoke(this, EventArgs.Empty); public void UnsubscribeAll() => Changed = null; } internal sealed class Subscriber { public void OnChanged(object? sender, EventArgs e) => Console.WriteLine("subscriber heard the event"); }

dotnet run

subscribed, alive: True
subscriber heard the event
unsubscribed, alive: False

The output is the real run. WeakReference.IsAlive is true while the publisher's delegate holds the subscriber, and false after the subscription is gone and the collector has run. The subscriber is created in a method that returns only the weak reference, so no local of Main keeps it alive: that is the detail that makes such a test honest, because a variable in the calling scope is a root the collector must respect.

Two caveats keep the result honest. Publisher.UnsubscribeAll is legal only inside the class that declares the event, which is why a form uses -= and a model can clear its own event. And a WeakReference may report true for an object that is unreachable but not yet collected: the flag means "not collected yet", so the Collect calls in the listing are part of the experiment, not decoration.

Exercises

  1. Add a second subscriber and print how many handlers the publisher holds before and after the removal.
  2. Remove the two GC.Collect calls and run the program again. What does IsAlive say, and why?
  3. Explain from the documentation why FormClosed is a better place for the -= than a Click handler on a Close button.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a delegate hold besides the method?

    Answer

    Its target, the object the method is called on

    That reference is why a subscription keeps a form alive.

  2. Which object keeps a form alive in the classic leak?

    Answer

    A long-lived publisher whose event holds the form's handler

    A model or a static event that outlives the form keeps its target reachable.

  3. What does -= do when there is no matching subscription?

    Answer

    Nothing, without an exception

    The removal is safe to repeat, which is why it belongs in FormClosed and Dispose.

  4. Why does a lambda written twice not unsubscribe?

    Answer

    Each lambda is a different delegate instance

    Store the lambda in a field when it must be removed.

  5. Where does a form's -= of a long-lived publisher belong?

    Answer

    In FormClosed or Dispose

    It must run for every way the form can close.

  6. Why must a timer be stopped before it is disposed?

    Answer

    A disposed but enabled timer can raise ObjectDisposedException when it ticks

    The tick comes from the running timer, not from its handler.

  7. What does WeakReference.IsAlive mean?

    Answer

    The object has not been collected yet

    An unreachable object may still be uncollected, which is why the run collects first.

  8. What did the run print after the unsubscription?

    Answer

    unsubscribed, alive: False

    The collector ran and the subscriber was collected.

  9. Why is the subscriber created inside a method that returns only the weak reference?

    Answer

    A local of the calling method would be a root the collector must respect

    The experiment is only honest if nothing else roots the object.

  10. Which symptom shows a form leak?

    Answer

    Memory grows with every opening and old forms still react to events

    The closed form is still subscribed, so it still hears and still exists.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev