使用no-op lambda表达式初始化事件是否会阻止GC? [英] Does using a no-op lambda expression for initializing an event prevent GC?

查看:110
本文介绍了使用no-op lambda表达式初始化事件是否会阻止GC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用以下结构声明事件:

One can use the following construct for declaring an event:

public class MyClass
{
    public event EventHandler<EventArgs> SomeEvent = (s,e) => {};

    public void SomeMethod ()
    {
        // Do something interesting... ;)
        SomeEvent (this, new EventArgs);
    }
}

这允许引发事件,而无需检查事件是否为空.

That allows raising the event without the need to check if the event is null.

现在,假设对象A持有对MyClass对象的引用,注册该事件,然后在以后取消注册.

Now, let's say that an object A holds a reference to an object of MyClass, registers for the event and then unregisters it later on.

var myClass = new MyClass();
myClass.SomeEvent += MyHandler;
...
myClass.SomeEvent -= MyHandler;
myClass = null;

即使事件中仍然存在无操作lambda表达式,GC也会收集myClass吗?

Will the GC collect myClass even if there is a no-op lambda expression still on the event?

我猜是这样,因为对象根不再被其他对象引用...任何人都可以确认或证明吗?

I guess so because the object root is no longer reference by other objects... Can anyone confirm or prove otherwise?

推荐答案

使用问题中的代码,即使您不退订,GC也会收集myClass.这种关系是相反的. MyClass的事件拥有对订户的引用,因此从理论上讲,您应该担心订户没有被收集.如果您取消订阅,则将收集该订阅者.

With the code in the question the GC will collect myClass even if you don't unsubscribe. The relation is the other way around. MyClass's event holds reference to the subscriber so theoretically you should be worried about the subscriber not being collected. If you do unsubscribe the subscriber will be collected.

这篇关于使用no-op lambda表达式初始化事件是否会阻止GC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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