2

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?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

I've already been Skeeted twice this afternoon and it is only 15:45 here :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.