Event patterns, pitfalls (memory leaks)
Spot and fix event pitfalls: unsubscribe to avoid memory leaks, store delegate references to remove them, and use an IDisposable subscription pattern.
Event patterns, pitfalls (memory leaks) is a free C# Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Pitfalls overview
Goal: Use events safely.
- Unsubscribe to prevent memory leaks
- Keep a reference to the same handler to remove it
- Prefer a small IDisposable pattern for cleanup
- Avoid inline anonymous handlers you cannot detach
Unsubscribe to avoid leaks
Events hold references to subscribers. If the publisher lives long and you never detach, the subscriber cannot be collected.
using System;
public class Publisher
{
public event EventHandler Tick;
public void Fire()
{
EventHandler h = Tick;
if (h != null) h(this, EventArgs.Empty);
}
}
public class Subscriber
{
public void Handle(object s, EventArgs e)
{
Console.WriteLine("Handling tick");
}
public void Subscribe(Publisher p) { p.Tick += Handle; }
public void Unsubscribe(Publisher p) { p.Tick -= Handle; } // required to avoid leaks
}
public class Program
{
public static void Main(string[] args)
{
Publisher p = new Publisher();
Subscriber s = new Subscriber();
s.Subscribe(p);
p.Fire(); // prints once
s.Unsubscribe(p); // detach when done
s = null; // now eligible for GC in a real app
p.Fire(); // no output
}
}
Keep handler reference
To detach an anonymous handler, store it in a variable and pass the same instance to -=.
using System;
public class Button
{
public event EventHandler Click;
public void Simulate()
{
EventHandler h = Click;
if (h != null) h(this, EventArgs.Empty);
}
}
public class Program
{
public static void Main(string[] args)
{
Button b = new Button();
// BAD: cannot easily remove this later
// b.Click += (s, e) => Console.WriteLine("inline");
// GOOD: store the handler, attach, later detach the same instance
EventHandler saved = (s, e) => Console.WriteLine("saved");
b.Click += saved;
b.Simulate(); // prints "saved"
b.Click -= saved; // can remove because we kept the reference
b.Simulate(); // no output
}
}
Disposable subscription
Return an IDisposable from Subscribe. Use using to auto-unsubscribe.
using System;
public class Ticker
{
public event EventHandler Tick;
public IDisposable Subscribe(EventHandler handler)
{
Tick += handler;
return new Unsubscriber(this, handler);
}
private sealed class Unsubscriber : IDisposable
{
private Ticker _t;
private EventHandler _h;
private bool _done;
public Unsubscriber(Ticker t, EventHandler h) { _t = t; _h = h; }
public void Dispose()
{
if (!_done)
{
_t.Tick -= _h;
_done = true;
}
}
}
public void Fire()
{
EventHandler h = Tick;
if (h != null) h(this, EventArgs.Empty);
}
}
public class Program
{
public static void Main(string[] args)
{
Ticker t = new Ticker();
using (t.Subscribe((s, e) => Console.WriteLine("tick")))
{
t.Fire(); // prints once
}
t.Fire(); // nothing after disposal
}
}
try/finally detach
Use try/finally when a handler must be detached even if an exception is thrown.
using System;
public class Alarm
{
public event EventHandler Ring;
public void Trigger()
{
EventHandler h = Ring;
if (h != null) h(this, EventArgs.Empty);
}
}
public class Program
{
public static void Main(string[] args)
{
Alarm a = new Alarm();
EventHandler h = (s, e) => Console.WriteLine("ring");
a.Ring += h;
try
{
a.Trigger(); // do work with subscription active
}
finally
{
a.Ring -= h; // always detach
}
a.Trigger(); // no output
}
}
Tips to avoid leaks
Tips:
- Subscribers should own their unsubscription (Dispose, finally, or explicit method).
- Avoid subscribing with inline anonymous handlers you cannot remove.
- Be careful with static events; they often outlive objects.
- Keep handlers short; do not block the publisher.
Leak cause with events
Recap
Recap: Unsubscribe to prevent leaks, store handler references to remove them, and prefer disposable or finally-based cleanup patterns for safe event lifetimes.
Frequently asked questions
Is the “Event patterns, pitfalls (memory leaks)” lesson free?
Yes — the full text of “Event patterns, pitfalls (memory leaks)” is free to read here on the web, and the C# Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Event patterns, pitfalls (memory leaks)”?
Spot and fix event pitfalls: unsubscribe to avoid memory leaks, store delegate references to remove them, and use an IDisposable subscription pattern. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Event patterns, pitfalls (memory leaks)” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- delegate, Action/Func, closures
- Events: publish/subscribe, event keyword
- Event patterns, pitfalls (memory leaks)