视图模型调用中的调用方法占用/消耗大量时间

时间:2011-01-13 21:00:41

标签: wpf multithreading mvvm background caliburn.micro

嗨,我试着解决这个问题。我有MVVM应用程序与MVVM设计。我使用Caliburn Micro框架和注射MEF。

在WPF应用程序中,我使用来自外部程序集的服务。它运作良好。

问题是。我将可观察字典绑定到列表框。列表框可以包含0到400个项目。 我在listbox项目上有数据模板,它包含image和som texbox。列表框就像 Skype中的联系人列表或google talk。

我从服务中调用每3-4秒方法,将新数据作为字典返回。使用此数据aj刷新列表框。

我的代码看起来像这样的视图模型:

      private DispatcherTimer _dispatcherTimer;
            private MyObservableDictionary<string, UserInfo> _friends;
            //temp
            private MyObservableDictionary<string, UserInfo> _freshFriends;

    //bind on listbox
            public MyObservableDictionary<string, UserInfo> Friends
            {
                get { return _friends; }
                set
                {
                    _friends = value;
                    NotifyOfPropertyChange(() => Friends);
                }
            }

    //in constructor of view model I have this:
                _dispatcherTimer = new DispatcherTimer();
                _dispatcherTimer.Tick += DispatcherTimer_Tick;
                _dispatcherTimer.Interval = TimeSpan.FromSeconds(3);
                _dispatcherTimer.Start();

// on timer tick I call method from service
        private void DispatcherTimer_Tick(object sender, EventArgs eventArgs)
        {

            //get new data from server
            //method GetFriends take much of time
            _freshFriends = _service.GetFriends(Account);

            //delete old data
            _friends.Clear();

            //refresh
            foreach (var freshFriend in _freshFriends)
            {
                Friends.Add(freshFriend);

            }
        }

正如我所说的,问题是来自服务的方法GetFriends需要花费大量时间而我的应用程序会冻结。

怎样才能解决这个问题?在winforms应用程序中我使用后台工作程序,但这是我的第一个MVVM应用程序。它存在任何“模式”或“设计”如何在视图模型类中消耗大量时间的调用方法?在另一个线程中调用此方法?

1 个答案:

答案 0 :(得分:0)

正如其他人所建议的那样,您可以在WPF应用中使用BackgroundWorker,或者如果您使用的是.NET 4,则使用Task Parallel Library。与这里的BackgroundWorker - http://nitoprograms.blogspot.com/2010/06/reporting-progress-from-tasks.html

相比,Stephen Cleary在TPL上有一篇不错的帖子