c# dispose notification - Do event handlers stop garbage collection from occurring?





2 Answers

Yes, pClass will be garbage collected. The event subscription does not imply that any reference exists to pClass.

An so no, you will not have to detach the handler in order for pClass to be garbage collected.

remove weakreference anonymous

If I have the following code:

MyClass pClass = new MyClass();
pClass.MyEvent += MyFunction;
pClass = null;

Will pClass be garbage collected? Or will it hang around still firing its events whenever they occur? Will I need to do the following in order to allow garbage collection?

MyClass pClass = new MyClass();
pClass.MyEvent += MyFunction;
pClass.MyEvent -= MyFunction;
pClass = null;



pClass will be garbage collected. However, if the code snippet above is inside another class, the instance of that class might not be cleared if you do not set pClass to null.




Related