Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

lambda

events

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?

like image 535
Stécy Avatar asked Jan 27 '26 20:01

Stécy


2 Answers

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.

like image 187
Jon Skeet Avatar answered Jan 29 '26 08:01

Jon Skeet


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.

like image 42
Stilgar Avatar answered Jan 29 '26 10:01

Stilgar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!