开发者

Does using a no-op lambda expression for initializing an event prevent GC?

开发者 https://www.devze.com 2023-02-10 00:44 出处:网络
One can use the following construct for declaring an event: public class MyClass { public event EventHandler<EventArgs> SomeEvent = (s,e) => {};

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 in开发者_StackOverflowteresting... ;)
        SomeEvent (this, new EventArgs);
    }
}

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

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;

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?


The instance of MyClass could be collected even if you hadn't removed the "real" handler.

The normal "leak" with events is that the event publisher (MyClass in this case) has a reference to another object via the subscribed event handlers. Events don't prevent the publisher from being garbage collected. The no-op lambda certainly has no effect on this.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消