平台: WPF, .NET 4.0, C# 4.0
问题:在Mainwindow.xaml中,我有一个ListBox绑定到Customer集合,该集合当前是一个ObservableCollection <Customer>.
ObservableCollection<Customer> c = new ObservableCollection<Customer>();
此集合可以通过多个源进行更新,如FileSystem,WebService等.
为了允许并行加载Customers,我创建了一个帮助类
public class CustomerManager(ref ObsevableCollection<Customer> cust)
内部为每个客户源生成一个新任务(来自并行扩展库),并将新的Customer实例添加到客户集合对象(由ref传递给它的ctor).
问题是ObservableCollection <T>(或任何集合)不能在UI线程以外的调用中使用并遇到异常:
"NotSupportedException - 这种类型的CollectionView不支持从与Dispatcher线程不同的线程更改其SourceCollection."
我试过用了
System.Collections.Concurrent.ConcurrentBag<Customer>
集合但它没有实现INotifyCollectionChanged接口.因此我的WPF UI不会自动更新.
那么,是否有一个集合类可以实现属性/集合更改通知,还允许来自其他非UI线程的调用?
通过我最初的bing /谷歌搜索,没有提供开箱即用.
编辑:我创建了自己的集合,它继承自ConcurrentBag <Customer>,并且还实现了INotifyCollectionChanged接口.但令我惊讶的是,即使在单独的任务中调用它之后,WPF UI也会挂起,直到任务完成.是不应该并行执行任务而不阻止UI线程?
提前感谢您的任何建议.
wpf .net-4.0 observablecollection task-parallel-library c#-4.0
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
Run Code Online (Sandbox Code Playgroud)
我正在添加/删除不在UI线程上的ObservableCollection.
我有一个方法名称EnqueueReport添加到colleciton和DequeueReport从集合中删除.
步骤流程如下: -
我在C#库中并不多.有人可以指导我吗?