如果不再引用的父对象持有对仍然存在的对象的引用(例如在其他视图模型中引用的单例服务),它是否将不符合收集条件?
我还没有找到关于 GC 的明确解释。我的倾向是一切都保持原样,因为 ParentViewModel 不“拥有”该服务,它仍然会被回收。
考虑这些场景..
public class MainClass
{
public SingletonService SingletonService{ get; }
public void DoSomething()
{
using (ParentViewModel parentVM as new ParentViewModel(this.SingletonService))
{
// Work.
}
}
}
public class ParentViewModel : INotifyPropertyChanged, IDiposable
{
private readonly SingletonService _service;
public ParentViewModel(SingletonService singleton)
{
this._service = _service;
}
public void Dispose(bool disposing)
{
// Will my readonly reference to a living singleton prevent the ParentViewModel from being reclaimed?
}
}
我对活动单例的只读引用会阻止 ParentViewModel 被回收吗?
public class ParentViewModel : INotifyPropertyChanged, IDiposable
{
public SingletonService SingletonService{ get; }
public void Dispose(bool disposing)
{
// Do I need to null the SingletonServiceproperty to allow for ParentViewModel to be reclaimed?
// What if SingletonService has bindings to a view?
}
public bool SomeValue
{
get => this.SingletonService.OtherValue
}
}
我是否需要清空 SingletonService 属性以允许回收 ParentViewModel?
如果 SingletonService 绑定到视图怎么办?
我是否还需要将 SomeValue 设置为 null,因为它使用服务进行绑定?
GC将回收所有不可访问的内存。
由于引用是单向的,单例(以及基本上任何其他对象)不知道
ParentViewModel
的存在,因此 GC 将释放它,而不会对程序产生任何影响。