0

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 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?

  • 2
    BackgroundWorker works just as well in WPF as it does in WinForms. – Wonko the Sane Jan 13 '11 at 21:46
  • Exactly as @Wonko said - you can spawn your service request on another thread (such as one in the ThreadPool), use BackgroundWorker, etc. - when the results have returned, notify your main UI thread and populate the ListBox. This is a threading problem, not a WPF / MVVM problem. – Matt Jordan Jan 13 '11 at 22:10

1 Answers1

0

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

devdigital
  • 34,151
  • 9
  • 98
  • 120