更新一个ObservableCollection在一个单独的线程线程、ObservableCollection

2023-09-02 21:25:48 作者:狡猾哥哥

在一个WPF应用程序一个ObservableCollection填充和更新LINQ到SQL查询。然后,UI对象是从该的ObservableCollection使用值进行更新。

In a WPF application an ObservableCollection is filled and updated by LINQ to SQL queries. Then UI objects are updated using values from this ObservableCollection.

是否有可能和合理的更新此的ObservableCollection通过LINQ到SQL查询操作在一个单独的线程被处决?

Is it possible and reasonable that operations of updating this ObservableCollection by LINQ to SQL queries were executed in a separate thread?

如果是的,将在这种情况下,它是一个,这样的ObservableCollection的同一实例? (我的意思是,如果它是不一样的一个用于从LINQ的datacontext取值和一个用于提供值更新用户界面,那么我将无法更新UI)

If yes, will, in this case, it be one and the same instance of this ObservableCollection? (I mean, if it is not the same one for taking values from LINQ datacontext and the one for giving values to update UI, then I will not be able to update UI)

推荐答案

通过内置的的ObservableCollection< T> 类,你不能改变从内容如果单独的线程将UI绑定到集合,它抛出一个 NotSupportedException异常(但更改通知的藏品性质正常工作)。我写了一个 AsyncObservableCollection&LT ; T> 类来处理这种情况。它通过调用事件处理程序的UI同步上下文

With the built-in ObservableCollection<T> class, you can't change the content from a separate thread if the UI is bound to the collection, it throws a NotSupportedException (but change notification for properties of collection items works fine). I wrote an AsyncObservableCollection<T> class to handle this case. It works by invoking the event handlers on the UI synchronization context