Joa*_*nge 32 .net c# parallel-processing multithreading observablecollection
我正在使用BackgroundWorker更新,ObservableCollection但它给出了这个错误:
"这种类型
CollectionView不支持SourceCollection从与Dispatcher线程不同的线程对其进行更改 ."
用最少的工作量来解决这个问题的最佳和最优雅的方法是什么.我不想写低级别的基于锁的多线程代码.
我在网上看到了一些解决方案,但它们已有几年的历史了,所以不确定解决这个问题的最新共识是什么.
小智 36
如果在构造函数中初始化集合,它将位于默认的Application线程上.
要调用主线程,您可以执行以下操作:
Application.Current.Dispatcher.Invoke((Action)(() =>
{
//Do something here.
}));
Run Code Online (Sandbox Code Playgroud)
你必须将Anonymous委托作为一个动作,否则会混淆¯\ _O_o /¯
如果您使用的是Async CTP,则可以执行此操作
Application.Current.Dispatcher.InvokeAsync(()=>
{
//Do something here.
});
Run Code Online (Sandbox Code Playgroud)
dje*_*eeg 12
如果是MVVM
public class MainWindowViewModel : ViewModel {
private ICommand loadcommand;
public ICommand LoadCommand { get { return loadcommand ?? (loadcommand = new RelayCommand(param => Load())); } }
private ObservableCollection<ViewModel> items;
public ObservableCollection<ViewModel> Items {
get {
if (items == null) {
items = new ObservableCollection<ViewModel>();
}
return items;
}
}
public void Load() {
BackgroundWorker bgworker = new BackgroundWorker();
bgworker.WorkerReportsProgress = true;
bgworker.DoWork += (s, e) => {
for(int i=0; i<10; i++) {
System.Threading.Thread.Sleep(1000);
bgworker.ReportProgress(i, new List<ViewModel>());
}
e.Result = null;
};
bgworker.ProgressChanged += (s, e) => {
List<ViewModel> partialresult = (List<ViewModel>)e.UserState;
partialresult.ForEach(i => {
Items.Add(i);
});
};
bgworker.RunWorkerCompleted += (s, e) => {
//do anything here
};
bgworker.RunWorkerAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32160 次 |
| 最近记录: |