简体   繁体   中英

Does a PropertyChangedEventHandler keep my custom control from being garbage collected?

I am fairly new to WPF, and I wondered listening for property changes will keep my custom control from being garbage collected...

Essentially, I listen to events like this:

obj.PropertyChanged += this.The_PropertyChanged;

I am afraid that the control in which I execute the code not be able to be garbage collected while obj still exists, as obj.PropertyChanged holds a reference to this . Is this correct? If so, what is the correct way to avoid this? If I am informed correctly, there is no Dispose() method that could be overridden to be called when the Control is removed from the screen, so there is no obvious location to remove this.The_PropertyChanged from obj.PropertyChanged ...

Yes, you are correct. obj will have a reference to "this" and therefore "this" will not get garbage collected. The solution is:

obj.PropertyChanged -= this.The_PropertyChanged;

and you would place that code where "this" is Closed, Disposed, or else wise no longer going to be around.

So for the control, if the Window that hosts the control is closed that could be where you place the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM