难道事件处理程序,从存在的阻止垃圾回收?垃圾、存在、事件、程序

2023-09-02 10:15:36 作者:叹落笔

如果我有以下的code:

  MyClass的pClass =新MyClass的();
pClass.MyEvent + = MyFunction的;
pClass = NULL;
 

威尔pClass被垃圾收集?还是会流连时,他们仍然发生的射击事件?我需要做到以下几点,以便让垃圾收集?

  MyClass的pClass =新MyClass的();
pClass.MyEvent + = MyFunction的;
pClass.MyEvent  -  = MyFunction的;
pClass = NULL;
 
WeakHashMap垃圾回收问题

解决方案

有关的具体问题将pClass被垃圾回收:事件订阅对pClass收集没有影响(作为发行人)

有关的GC一般(特别是,靶):这取决于MyFunction的是静态的还是基于实例

一个委托(如事件订阅),以一个实例方法包括引用的实例。所以,是的,事件订阅将prevent GC。然而,一旦发布事件(pClass以上)的对象是符合回收,这不再是一个问题。

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

  publisher.SomeEvent + = target.SomeHandler;
 

然后发布者,将让目标活着,但目标不会保持发行人活着。

因此​​,没有:如果pClass将要被收集无论如何,没有必要取消订阅的听众。然而,如果是pClass长寿命(比MyFunction的实例更长),然后pClass可以保持该实例活着,所以它的将的必要取消订阅如果要收集的对象。

静态事件,但是,由于这个原因,与基于实例的处理程序中使用时是非常危险的。

If I have the following code:

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

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;

解决方案

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

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

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;

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

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.

 
精彩推荐
图片推荐