【发布时间】:2020-04-03 19:45:52
【问题描述】:
我想知道下面的代码是否会产生泄漏:Parent 类有Child 类的列表。 Child 对象使用 PropertyChangedEventManager.AddHandler 来通知聚合 Parent 对象中的属性更改。如果这些聚合实例从不调用RemoveHandler,会不会产生泄漏?
我了解the GC is based upon reachability, not reference counting,但显然PropertyChangedEventManager 正在某处维护处理程序订阅者列表。那么如果我不调用RemoveHandler,该列表如何清理?
我的代码所做的类似这样的简化版本:
public class Parent : INotifyPropertyChanged
{
public Parent()
{
_children = new List<Child>();
_children.Add(new Child(this));
}
public event PropertyChangedEventHandler PropertyChanged;
public bool Value
{
get => _value;
set
{
_value = value;
PropertyChanged?.Invoke(new PropertyChangedEventArgs("Value"));
}
}
private List<Child> _children
}
public class Child
{
public Child(Parent parent)
{
// Will failing to undo this with RemoveHandler cause a leak?
PropertyChangedEventManager.AddHandler(r, OnValueChange, "Value");
}
void OnValueChanged(object sender, PropertyChangedEventArgs e)
{
// Do something...
}
}
【问题讨论】:
标签: c# .net garbage-collection inotifypropertychanged