开发者

Call method in view model call which take/consume much of time

Hi I try solve this situation. I have WPF app with MVVM design. I use Caliburn Micro framework and on injection MEF.

In WPF app I use service from external assembly. It works good.

Problem is. I bind observable dictionary to listbox. Listbox can consist from 0 to 400 items. I have data template on listbox item it consist with image and som texbox. Listbox is like contact list in skype or google talk.

I call every 3-4 sec method from service, wich returns new data as dictionary. An with this data aj refresh Listbox.

My code look in view model like this:

      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 开发者_StackOverflow中文版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);

            }
        }

As I said, problem is that method GetFriends from service take much of time and my app freezes.

How can solve this problem? In winforms app I use background worker, but this is my first WPF app with MVVM. It exist any "patern" or "design" how call method which consume much of time in view model class? Call this method in another thread?


As others have suggested, you can use a BackgroundWorker in a WPF app, or if you are using .NET 4, then use the Task Parallel Library. Stephen Cleary has a nice post on the TPL compared to BackgroundWorker here - http://nitoprograms.blogspot.com/2010/06/reporting-progress-from-tasks.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜