事件处理程序会阻止垃圾收集的发生吗? [英] Do event handlers stop garbage collection from occurring?

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

问题描述

如果我有以下代码:

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;

推荐答案

针对具体问题Will pClass会被垃圾收集":事件订阅对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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆