本文介绍了事件处理程序是否停止发生垃圾回收?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码:

If I have the following code:

MyClass pClass = new MyClass();
pClass.MyEvent += MyFunction;
pClass = null;

pClass会被垃圾收集吗?或者它会在它发生的时候继续发射它的事件吗?为了允许垃圾收集,我需要执行以下操作吗?

Will pClass be garbage collected? Or will it hang around still firing its events whenever they occur? Will I need to do the following in order to allow garbage collection?

MyClass pClass = new MyClass();
pClass.MyEvent += MyFunction;
pClass.MyEvent -= MyFunction;
pClass = null;


推荐答案

:事件订阅对pClass(作为发布者)的集合没有任何影响。

For the specific question "Will pClass be garbage collected": the event subscription has no effect on the collection of pClass (as the publisher).

对于一般的GC(特别是目标):取决于MyFunction是静态的或基于实例的。

For GC in general (in particular, the target): it depends whether MyFunction is static or instance-based.

实例方法的委托(例如事件订阅)包含对实例的引用。所以是的,一个事件订阅会阻止GC。但是,只要发布事件的对象(上面的pClass)有资格收集,就不会有问题。

A delegate (such as an event subscription) to an instance method includes a reference to the instance. So yes, an event subscription will prevent GC. However, as soon as the object publishing the event (pClass above) is eligible for collection, this ceases to be a problem.

请注意,这是单向的;即如果我们有:

Note that this is one-way; i.e. if we have:

publisher.SomeEvent += target.SomeHandler;

然后publisher会保持target活着,但target不会保留publisher活着。

then "publisher" will keep "target" alive, but "target" will not keep "publisher" alive.

所以不行:如果pClass将要被收集,则不需要取消订阅听众。但是,如果pClass长期存在(比使用MyFunction的实例长),那么pClass可以使该实例保持活动状态,因此如果希望收集目标,它必须来取消订阅。

So no: if pClass is going to be collected anyway, there is no need to unsubscribe the listeners. However, if pClass was long-lived (longer than the instance with MyFunction), then pClass could keep that instance alive, so it would be necessary to unsubscribe if you want the target to be collected.

然而,由于这个原因,静态事件在与基于实例的处理程序一起使用时非常危险。

Static events, however, for this reason, are very dangerous when used with instance-based handlers.

这篇关于事件处理程序是否停止发生垃圾回收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 22:51