本文介绍了在什么情况下是由必要的事件分离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如果我在对象连接到事件的影响完全清楚

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 + =新System.ComponentModel.CancelEventHandler(MainWindow_Closing);

公共事件的EventHandler OnMyCustomEvent =代表{};

我假设,当你的对象被处置,或者垃圾回收,该功能被释放,并会自动分离的事件。

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;),已经被从

例子分离:
连接到一个计时器经过的事件,这你只响应一次。我会假设你需要定时器存储在一个局部变量,因此您可以在事件触发后脱落经过事件。因此,在本地方法范围宣布计时器像这样将导致泄漏:

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 =新System.Timers .Timer(1000);
myDataTimer.Elapsed + =新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:


  • 当您订阅事件,该事件的所有者(发布者)一般保持一个参考到委托你订阅用。

  • 如果您使用实例方法为代表的动作,然后委托有它的目标对象的引用。

这意味着,如果你写的:

This means that if you write:

publisher.SomeEvent += subscriber.SomeMethod;



然后用户将没有资格垃圾收集之前出版商是,除非你以后退订。

Then subscriber won't be eligible for garbage collection before publisher is unless you unsubscribe later.

请注意,在许多情况下,用户就是这个

Note that in many cases, subscriber is just this:

publisher.SomeEvent += myDataTimer_Elapsed;



等同于:

is equivalent to:

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.

这篇关于在什么情况下是由必要的事件分离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:28