0

I am in a process of extending ObservableCollection<T>, which will notify collection change back to UI thread from ViewModel in an ideal MVVM scenario. To achieve this, I am thinking of resolving UI Dispatcher through some IOC and eventually use the resolved Dispatcher instance within my custom observable type.

Draft will look like this;

class SafeObservableCollection<T>: ObservableCollection<T>
{
    public SafeObservableCollection(IDispatcher currentDispatcher)//maybe an instance of Dispatcher
    {
     //assign resolved dispatcher to a private member
    }
}

Assumption: (a) WPF application which uses one Dispatcher/UIThread. (b) I am not thinking of any deviation (APM/EPM using BackgroundWorker) apart from overriding base class members of ObservableCollection

Question: Can you propose anything better to resolve Dispatcher instance while following the outlined code? Can you help me to nail down any possible design flaw? Such as memory leak, deadlock or anything which I overlooked. What should be / would be the lifetime of my Dispatcher instance if I decided to go with this approach.

4

2 回答 2

0

如果您使用的是 .NET 4.5,则不应发明新工具并使用可以做到这一点的现有功能。

//Creates the lock object somewhere
private static object _lock = new object();

...

//Enable the cross acces to this collection elsewhere
BindingOperations.EnableCollectionSynchronization(_persons, _lock);

现在您可以从任何线程访问 _persons 可观察对象。

还有 WPFExtensions 具有线程安全的 observable;http://wpfextensions.codeplex.com/

于 2013-05-18T04:56:52.333 回答
0

我认为您希望这样做以使其可单元测试(因为IDispatcher可以模拟)。如果没有,那么您也可以只使用Application.Current.Dispatcher调用回主线程。

注入一个IDispatcher解析为包装的混凝土的Application.Current.Dispatcher,不应该有任何内存泄漏、死锁等问题,并且很容易可测试/可模拟。

我建议只IDispatcher在你的SafeObservableCollection类中留下对的引用,而不是仅仅使用它来直接引用 UI 线程Dispatcher本身,因为你会失去可模拟性的好处。只需IDispatcher公开Dispatcher您需要的功能。

生命周期是你的选择——每个一个愚蠢的Dispatcher包装器实例SafeObservableCollection应该没问题,但如果你特别偏执,你可以让你的 IoC 将它作为一个单例解决,没有任何问题。

于 2013-05-18T01:56:55.327 回答