避免短期视图模型上的弱事件管理器和内存泄漏



我有长寿模型,其属性使用视图显示。 我视图上的 DataContext 是一个生命周期较短的 ViewModel。

示例包括列表中的行视图模型。

为了避免内存泄漏,视图模型使用System.Windows.WeakEventManager订阅模型。

如果我正常订阅,长寿命模型将使视图模型保持活动状态。

在每个视图模型中使用 WeakEventManager 似乎非常麻烦。 该用例看起来像 WPF 的标准用例。我是否缺少 WPF 或 C# 的基本概念,这些概念可以帮助我在这里编写更好的代码?

这是一个最小的示例,说明了我现在所做的事情。

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//building would take place in a factory method
DataContext = new ShortLivedViewModel(new LongLivingModel());
}
}
public class ShortLivedViewModel : INotifyPropertyChanged
{
private string _myText;
public ShortLivedViewModel(LongLivingModel model)
{
model.SomeEvent += SomeEventHandler;
WeakEventManager<LongLivingModel, EventArgs>.AddHandler(model, nameof(LongLivingModel.SomeEvent),
SomeEventHandler);
}
public string MyText
{
get => _myText;
set
{
_myText = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(MyText)));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void SomeEventHandler(object sender, EventArgs e)
{
//The actual update content would come from the event args
MyText = Guid.NewGuid().ToString("N");
}
}
public class LongLivingModel
{
//the event does not matter too much so I omit the implementation that causes it
public EventHandler<EventArgs> SomeEvent = delegate { };
}

我的问题是,是否有一种不那么繁琐的方法可以从短寿命对象订阅长寿命对象。或者,如果 WPF 中缺少一些我为此提供的功能。

令我印象深刻的是,这将是标准情况。 我玩的是添加一个IDisposable接口,但这只让我知道何时调用 dispose 以便我可以取消订阅。

我正在寻找的可能是告诉 GC 订阅不计入视图模型的生命周期和取消订阅销毁的组合 - 或者更好的解决方案。

我认为父视图模型应该负责摆脱引用。

这是一个将更新推送到每个子视图模型的简单示例。当需要清理子项时,它会告诉父项删除其引用。

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//building would take place in a factory method
DataContext = new LongLivingModel();
LongLivingModel.AddChild();
LongLivingModel.AddChild();
}
}
public class ShortLivedViewModel : INotifyPropertyChanged
{
private readonly LongLivingModel longLivingModel;
public ShortLivedViewModel(LongLivingModel longLivingModel){
this.longLivingModel = longLivingModel;
}
private string _myText;
public string MyText
{
get => _myText;
set
{
_myText = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(MyText)));
}
}
public void Remove(){
longLivingModel.Remove(this);
}
// INotifyPropertyChanged implementation
}
public class LongLivingModel
{
public ObservableCollection<ShortLivedViewModel> ChildViewModels { get; } = new ObservableCollection<ShortLivedViewModel>();
public void AddChild(){
ChildViewModels.Add(new ShortLivedViewModel(this));
}
public void RemoveChild(ShortLivedViewModel shortLivedViewModel) {
ChildViewModels.Remove(shortLivedViewModel);
}
public void PushToChildren(){
foreach(ShortLivedViewModel shortLivedViewModel in ChildViewModels){
shortLivedViewModel.MyText = Guid.NewGuid().ToString("N");
}
}
}

最新更新