简体   繁体   English

在短期视图模型上避免 WeakEventManager 和内存泄漏

[英]Avoiding WeakEventManager and memory leaks on short lived viewmodels

I have long living models with properties displayed using a view.我有使用视图显示属性的长期存在的模型。 The DataContext on my view is a ViewModel with a short lifespan.我视图上的 DataContext 是一个生命周期很短的 ViewModel。

Examples include row viewmodels in lists.示例包括列表中的行视图模型。

To avoid memory leaks the viewmodels subscribe to models using System.Windows.WeakEventManager .为了避免内存泄漏,视图模型使用System.Windows.WeakEventManager订阅模型。

If I were to subscribe normally the long living model would keep the viewmodel alive.如果我要正常订阅,长寿模型将使视图模型保持活动状态。

Using the WeakEventManager in about every viewmodel seems very cumbersome.在每个视图模型中使用 Wea​​kEventManager 似乎非常麻烦。 The usecase looks like a standard usecase for WPF.用例看起来像 WPF 的标准用例。 Am I missing a fundamental concept of WPF or C# that would help me writing better code here?我是否错过了 WPF 或 C# 的一个基本概念,可以帮助我在这里编写更好的代码?

Here is a minimal Example that Illustrates what I do right now.这是一个最小的示例,说明了我现在所做的事情。

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 { };
}

My question is if there is a less cumbersome way of subscribing to a long living object from a short living object.我的问题是,是否有一种不那么麻烦的方法可以从短寿命对象订阅长寿命对象。 Or if there is some facility in WPF that I am missing for this.或者,如果 WPF 中有一些我缺少的工具。

It strikes me that this would be the standard case.我觉得这将是标准情况。 What I played around with is adding an IDisposable interface but that just leaves me with tacking when to call dispose so I can unsubscribe.我玩的是添加一个IDisposable接口,但这只是让我确定何时调用 dispose 以便我可以取消订阅。

What I am looking for may be a combination of telling the GC that subscriptions do not count for the lifetime of the viewmodel and unsubscribing on destruction - or an even better solution.我正在寻找的可能是告诉 GC 订阅不计入视图模型的生命周期和取消订阅销毁的组合 - 或者更好的解决方案。

I think the parent viewmodel should be responsbile for getting rid of references.我认为父视图模型应该负责摆脱引用。

This is a simple example that pushes an update to each child viewmodel.这是一个向每个子视图模型推送更新的简单示例。 When a child needs to be cleaned up, it tells the parent to remove its reference.当需要清理子项时,它会告诉父项删除其引用。

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");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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