0

嗨,我尝试解决这种情况。我有 MVVM 设计的 WPF 应用程序。我使用 Caliburn Micro 框架和注入 MEF。

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

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

我从服务中调用每 3-4 秒的方法,将新数据作为字典返回。用这个数据 aj 刷新 Listbox。

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

      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 的 WPF 应用程序。它存在任何“模式”或“设计”如何调用在视图模型类中消耗大量时间的方法?在另一个线程中调用此方法?

4

1 回答 1

0

正如其他人所建议的那样,您可以BackgroundWorker在 WPF 应用程序中使用 a ,或者如果您使用的是 .NET 4,则使用Task Parallel LibraryBackgroundWorker与此处相比,Stephen Cleary 在 TPL 上有一篇不错的帖子- http://nitoprograms.blogspot.com/2010/06/reporting-progress-from-tasks.html

于 2011-01-14T00:16:26.050 回答