我使用Dictionary
的目的是宽松地保存引用,而不是使用像Windows Forms
这样的传统查找强烈引用。
但是,我已经测试了一种情况来仔细检查该功能,并且看起来好像失败了。以下代码基于public class SampleModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string property = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
string _name;
public string Name
{
get
{
return _name;
}
set
{
if(_name != value)
{
_name = value;
OnPropertyChanged();
}
}
}
}
,但是您可以尝试使用所需的任何框架或平台对其进行调整:
示例模型 :
//at some class level scope
BindingSource _bs;
ConditionalWeakTable<BindingSource, object> _lookup =
new ConditionalWeakTable<BindingSource, object>();
public void Test(){
_bs = new BindingSource();
var item = new SampleModel();
_bs.Add(item);
_bs.ListChanged += (s,e) =>
{
MessageBox.Show("Failed! There is some memory leak");
};
_lookup.Add(_bs, new object());
//here the old instance is not referenced by any variable
_bs = new BindingSource();
//try collecting all collectable things
GC.Collect();
GC.WaitForPendingFinalizers();
//try changing the item's property
//the old instance of BindingSource if not collected will still
//fire the ListChanged event and the handler will show a message box
//as you see above.
item.Name = "some name";
}
主代码 :
Test
测试应用程序以发布模式构建,以确保GC正常运行。
结果是消息框始终显示。
预期结果是未显示任何消息框。
请注意,new Uint8Array
方法在每次运行测试应用程序时仅运行一次。
您能在这里解释一些错误吗?