Does using a no-op lambda expression for initializ

2019-07-19 17:29发布

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.

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?

标签: c# events lambda
2条回答
男人必须洒脱
2楼-- · 2019-07-19 17:43

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.

查看更多
Rolldiameter
3楼-- · 2019-07-19 17:48

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.

查看更多
登录 后发表回答