明确的事件添加/删除,误解?误解、明确、事件

2023-09-03 16:54:43 作者:抱恙

我一直在寻找到内存管理最近很多东西,一直在寻找如何事件管理,现在,我看到了明确的添加/删除语法事件订阅。

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.

我认为这是pretty的简单,添加/删除只是让我来执行其他逻辑,当我订阅和退订?我会得到它,还是有更多的吗?

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.

清理订阅(不是事件句柄)是最好的实现做了的IDisposable

Cleaning up subscriptions (not "event handles") is best done by implementing IDisposable.

更新:有一些变化在其对象应该实施的IDisposable 。在RX队从设计的角度做出的最好的决定:订阅本身是的IDisposable 。普通的.NET事件没有那么重presents认购的对象,所以选择的是发布者(该事件被定义的类)和用户(通常是类包含成员函数所预订)之间。虽然我的设计本能preFER使得用户的IDisposable ,最现实code使得出版商的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.

(也就是说,如果code其实清理事件订阅的。大多数code没有。)

(That is, if the code actually cleans up event subscriptions at all. Most code does not.)