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.
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
}
}
All lessons in this course
- delegate, Action/Func, closures
- Events: publish/subscribe, event keyword
- Event patterns, pitfalls (memory leaks)