Explicit Event add/remove, misunderstood?

后端 未结 3 371
眼角桃花
眼角桃花 2021-01-02 00:57

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 subsc

3条回答
  •  北海茫月
    2021-01-02 01:36

    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 are IDisposable. 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 subscriber IDisposable, most real-world code makes the publisher IDisposable: 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.)

提交回复
热议问题