Unsubscribing from C# events can be a pain. It isn’t so bad when your event
handler is a simple static or instance method, because those methods are still
available when you’re ready to unsubscribe.
When you subscribe to an event using an anonymous delegate, however, things
get trickier. You’ve got to keep that delegate around so that you can remove
it from the event.
The Scope class can be a convenient
way to encapsulate the lifetime of an event, though it is a bit awkward,
because you have to declare a local variable for the event handler.
We’ve written an EventInfo class that encapsulates the add/remove behavior of
any event and makes it easy to create a Scope that unsubscribes to an event.
Here’s how EventInfo would be used:
Any class with events can expose static read-only EventInfo fields to help
clients with this pattern, but a client is certainly capable of creating
EventInfo instances on its own, since the EventInfo doesn’t manage the process
of raising the event at all.
If you’re using the Subscribe pattern a lot with a single event, the EventInfo
class is probably worth using. However, the real reason we created
EventInfo was to make it easier to subscribe to events with weak
references, which will be the subject of my next post.