每次刷新都会增加更新私有Observable Collection的时间

本文关键字:Observable Collection 时间 新私 更新 刷新 增加 | 更新日期: 2023-09-27 18:16:07

我有一个使用MVVM方法的WPF应用程序。

在我的一个视图模型中,我有一个私有的可观察集合,我将其设置为'new observableCollection',这是从一个查询中创建的,该查询通过使用NHibernate的ISession对象的存储库类获取数据。

我在我的视图模型中有一个私有的可观察集合,我想用从我的查询返回/创建的集合更新。

问题是,每次我调用我的方法来执行查询,更新私有对象(ObservableCollection)所花费的时间每次都更长。

我测试了查询在存储库中执行所花费的时间,它只有4或5秒。我正在使用延迟加载检索4500条记录。

所以我的问题是为什么时间会增加每次我调用我的刷新方法在视图模型?此外,我还应该补充说,在任务管理器中显示的内存使用也增加了,所以它几乎出现了内存泄漏?

代码示例如下:

ViewModel:

private static ObservableCollection<CustomerViewModel> _allCustomers;      
Expression<Func<Customer, bool>> expression2 = p => p.IsVisible == 'T';
_allCustomers = new ObservableCollection<CustomerViewModel>(
    from customer in ManyEntitiesRepository<Customer>.Instance.RetrieveAll(expression2)
    select new CustomerViewModel(customer));

库检索

    public virtual IList<T> RetrieveAll(Expression<Func<T, bool>> expression)
    {
        try
        {
            if (_allEntities != null)
            {
                foreach (T entity in _allEntities)
                    SessionProvider.Instance.GlobalSession.Evict(entity);
                _allEntities.Clear();
            }
            _allEntities = (from c in SessionProvider.Instance.GlobalSession.Query<T>().AsExpandable()
                            where expression.Invoke(c)
                            select c).ToList<T>();
            return _allEntities;
        }

每次刷新都会增加更新私有Observable Collection的时间

如前所述,视图模型的大小增加了一倍。当应用程序首次加载时,它从数据库加载了4689条记录。每次刷新完成后,从数据库中检索一组新的数据,就会加载另外4689个数据,以此类推……等等......这在内存泄漏方面是相当大的。

发生这种情况的原因是我在视图模型中注册了2条消息,我正在创建一个集合,这些消息引用了其他视图模型。当我在Ants内存分析器中跟踪它们时,这些消息虽然确实显示为"弱引用",但没有释放其他对象。

一旦我删除了这两个引用,就没有问题了。快速检索数据,无内存泄漏。

Messenger.Default.Register<BroadcastPropertyChanged<ControlContainerTemplate>>(this, (message) =>
        {
            //// Instance needs to find out if it is a real receiver
            if (_udfViewModel != null && _udfViewModel.ControlsValue.Any((c) => message.Sender == c))
                RaiseBooleanFlagsChanged();
        });
        Messenger.Default.Register<BroadcastPropertyChanged<ChargeTemplateViewModel>>(this, (message) =>
            {
                //// Instance needs to find out if it is a real receiver
                if (_chargeTemplates != null && _chargeTemplates.Any((c) => message.Sender == c))
                    RaiseBooleanFlagsChanged();
});

我正在使用Galasoft。MVVM Light Toolkit…它指出,消息不需要处置,因为它们是弱引用,但现在我显然要寻找一个替代方案,让我的视图模型通信,或者我将不得不看到如何注销这些消息之前,创建该视图模型的新集合。

检查:http://mvvmlight.codeplex.com/, Laurant已经确定了这个问题,我现在才看到:)但是他正在寻找解决这个问题在MVVM Light工具包的第4版,这样弱引用实际上是一个弱引用,视图模型可以被GC释放和收集。

谢谢

为了解决这个问题,我在我的私人集合中循环视图模型,并在每个集合上调用cleanup()。增加了额外的4秒左右的刷新时间,但总比你的内存被重复的视图模型堵塞,每次刷新查询时间增加20秒或更多要好。

                    foreach (XViewModel m in _xCollection)
                    {
                        m.Cleanup();
                     }

我将在接下来的几个月里密切关注v4的发布…

欢呼