Unsubscribing in C# is a question of identity, not syntax: which registration does -= actually match, and who owns its lifetime? The article works through duplicate handlers, wrapper delegates and captured dispatch snapshots against .NET 10 documentation.
Key points
- Outside the declaring type an event only offers += and -=; the backing delegate stays hidden.
- Field-like events hold null until the first handler, and Delegate.Remove drops only the last matching occurrence.
- Subscribing the same named handler twice therefore leaves one live registration after a single -=.
- A lambda wrapper is the registered delegate, so keep that wrapper value if you plan to unsubscribe.
- Invocation lists are immutable: a raise already in progress still calls handlers removed during dispatch.
- Removing a handler ends membership only; running async void work and cancellation need their own contract.
Real-world use
- A desktop or Blazor view that can be activated twice and would otherwise stack duplicate handler registrations.
- A singleton service whose event keeps a short-lived consumer object reachable long after its screen has closed.
- An adapter that converts EventHandler<MessageArgs> to an Action<string> and must store the wrapper to detach it later.
- A shutdown routine where the publisher may still be dispatching while handlers unsubscribe in the middle of a raise.
This summary was generated by the agent from the original post on Nick Cosentino (Dev Leader). The full text and all rights belong to its author and publisher. Go to original