我不确定我是否完全清楚附加到对象中的事件的含义.
I'm not sure if I'm entirely clear on the implications of attaching to events in objects.
这是我目前的理解,正确或详细:
This is my current understanding, correct or elaborate:
1.附加到本地类事件不需要分离
例子:
this.Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
公共事件 EventHandler OnMyCustomEvent = delegate { };
我假设当你的对象被释放或垃圾回收时,函数被释放并自动从事件中分离.
I'm assuming that when your object is disposed or garbage collected, the functions are deallocated and would automatically detach from the events.
<强>2.附加到您不再需要的对象 (= null;) 必须从中分离
示例:附加到计时器的 Elapsed 事件,您只响应一次.我假设您需要将 Timer 存储在局部变量中,以便在事件触发后分离 Elapsed 事件.因此,像这样在本地方法范围内声明计时器会导致泄漏:
Examples: Attaching to a timer's Elapsed event, which you only respond to once. I would assume you need to store the Timer in a local variable so you can detached the Elapsed event after the event fires. Thus, declaring the timer in a local method scope like so would result in a leak:
System.Timers.Timer myDataTimer = new System.Timers.Timer(1000);myDataTimer.Elapsed += new System.Timers.ElapsedEventHandler(myDataTimer_Elapsed);
3.将本地对象中的事件附加到您的类不需要处置?
例如,如果您有一个 ObservableCollection,您可以创建、监控并让它消失.如果您使用本地私有函数附加到 CollectionChanged 事件,当您的类被垃圾回收时,该函数不会释放,导致 ObservableCollection 也被释放吗?
For example, if you had an ObservableCollection that your creates, monitors, and lets die. If you attached to the CollectionChanged event using a local, private function, wouldn't this function deallocate when your class is garbage collected, causing the ObservableCollection to also be freed?
我确定在某些地方我已经停止使用对象并且未能从事件中分离(例如,我制作的计时器示例),因此我正在寻找有关其工作原理的更清晰的解释.
I'm sure I have places where I've stopped using objects and have failed to detach from an event (for example, the timer example I made), so I'm looking for a clearer explanation on how this works.
我认为你让它变得比它需要的更复杂.你只需要记住两件事:
I think you're making it more complicated than it needs to be. You just need to remember two things:
这意味着如果你写:
publisher.SomeEvent += subscriber.SomeMethod;
那么在 publisher
之前,subscriber
将没有资格进行垃圾回收,除非您稍后取消订阅.
Then subscriber
won't be eligible for garbage collection before publisher
is unless you unsubscribe later.
请注意,在许多情况下,subscriber
只是 this
:
Note that in many cases, subscriber
is just this
:
publisher.SomeEvent += myDataTimer_Elapsed;
相当于:
publisher.SomeEvent += this.myDataTimer_Elapsed;
假设它是一个实例方法.
assuming it's an instance method.
没有由于事件订阅的反向关系 - 换句话说,订阅者不会让发布者保持活动状态.
There is no reverse relationship just due to event subscription - in other words the subscriber doesn't keep the publisher alive.
顺便说一下,有关更多信息,请参阅 我关于事件和代表的文章.
See my article on events and delegates for more information, by the way.
这篇关于在什么情况下脱离事件是必要的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!