🤖 The AI Prompt That Hunts Down a Leaked Event Subscription
A memory leak from an object that subscribed to an event and never unsubscribed is one of the hardest bugs to spot by reading code top to bottom, because the subscribing line and the missing unsubscribe live in two completely different methods, often two different classes, and nothing about either one looks wrong in isolation.
🔎 The Problem
Prompt: "Here is [paste a class and the classes it interacts with]. For every += event subscription in this code, tell me: (1) where the matching -= unsubscribe is, if any, (2) whether the subscribing object's lifetime is shorter than the event source's lifetime, and (3) if it is, show me exactly where to add the unsubscribe call and whether IDisposable is the right place to put it."
✅ Fix: Why This Prompt Works
- It forces a pairing check (subscribe vs. unsubscribe) instead of asking the model to ‘find the memory leak’, which is too vague a target for it to search for reliably.
- Asking explicitly about relative object lifetimes is the actual root cause test for this class of bug — a short-lived subscriber tied to a long-lived publisher is the signature pattern every time.
- Requesting a specific fix location (and whether IDisposable fits) turns the answer into something you can act on immediately, rather than a general explanation of event leaks.
💡 Good to Know
- This works especially well on WPF/WinForms view models and on any publish-subscribe service registered as a singleton, since those are exactly where lifetime mismatches tend to hide.
The bug isn’t in the line that subscribes — it’s in the line that was supposed to exist somewhere else and doesn’t.





