wpf mvvm threading.Timer and TimerCallback problem

2019-09-04 18:56发布

I have a WPF application developed against the MVVM framework in which the ViewModel constructor set a Timer with a TimerCallback.

The TimerCallback retrieves an ObservableCollection and passes it to a field on the VM.

I have a CollectionViewSource which has its Source property set to the ObservableCollection. I am using a CollectionViewSource because I want to enable filtering on the Collection.

I have found that when the TimerCallback attempts to pass the ObservableCollection into the local field the Source property for the CollectionViewSource has an exception {"The calling thread cannot access this object because a different thread owns it."}.

I understand the exception but I have two problems:

  1. How to get around this problem?
  2. And more importantly why do I only get this issue when using a CollectionViewSource? If I remove the CollectionViewSource and make the ObservableCollection a public property then I get no such exception.

Any help appreciated! Thanks, Drammy

2条回答
时光不老,我们不散
2楼-- · 2019-09-04 19:32
  1. Use the DispatcherTimer instead of the timer class you are using now, and make sure you create it on the UI thread.
  2. Probably with just an ObservableCollection your UI is not updated.
查看更多
来,给爷笑一个
3楼-- · 2019-09-04 19:35

To partially answer your question, any updates on ObservableCollection that might be observed by UI elements must be dispatched through the UI thread. When I wish to do this in MVVM, my strategy is to inject a SynchronizationContext into the constructor of the ViewModel that I initialize during my application startup. This gives me a View-framework-independent way to dispatch updates that must be synchronized with the View.

查看更多
登录 后发表回答