I’ve been looking into memory management a lot recently and have been looking at how events are managed, now, I’m seeing the explicit add/remove syntax for the event subscription.
I think it’s pretty simple, add/remove just allows me to perform other logic when I subscribe and unsubscribe? Am I getting it, or is there more to it?
Also, while I’m here, any advice / best practices for cleaning up my event handles.
Add/remove syntax is commonly used to “forward” an event implementation to another class.
Cleaning up subscriptions (not “event handles”) is best done by implementing
IDisposable.UPDATE: There is some variation on which object should implement
IDisposable. The Rx team made the best decision from a design perspective: subscriptions themselves areIDisposable. Regular .NET events do not have an object that represents the subscription, so the choice is between the publisher (the class on which the event is defined) and the subscriber (usually the class that contains the member function being subscribed). While my design instincts prefer making the subscriberIDisposable, most real-world code makes the publisherIDisposable: it’s an easier implementation, and there may be cases where there isn’t an actual subscriber instance.(That is, if the code actually cleans up event subscriptions at all. Most code does not.)