c# - 从另一个线程更新 ObservableCollection 的最佳方法是什么?

标签 c# .net multithreading parallel-processing observablecollection

我正在使用 BackgroundWorker 更新 ObservableCollection 但它给出了这个错误:

"This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."

用最少的工作量解决这个问题的最佳和最优雅的方法是什么。我不想编写低级的基于锁的多线程代码。

我在网上看到过一些解决方案,但都是几年前的了,所以不确定这个问题的解决方案的最新共识是什么。

最佳答案

如果您在构造函数中初始化集合,它将在默认应用程序线程上。

要调用主线程,您可以这样做:

Application.Current.Dispatcher.Invoke((Action)(() =>
    {
       //Do something here.
    }));

你必须将 Anonymous 委托(delegate)作为一个 Action ,否则它会变得困惑 ¯\O_o/¯

如果您使用的是异步 CTP,那么您可以这样做

Application.Current.Dispatcher.InvokeAsync(()=>
    {
       //Do something here.
    });

关于c# - 从另一个线程更新 ObservableCollection 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5480372/

相关文章:

c# - 为什么 -2 % 360 在 C# 中给出 -2 而不是 358

c# - 如何在 .NET 中应用业务逻辑和数据绑定(bind)?

java - volatile 读取是否发生在 volatile 写入之前?

java - 在 Hadoop Mapreduce 的 MultithreadedMapper 类的内部线程映射器之间共享大对象?

c# - 如何检索事件的所有方法?

c# - 将 List<SomeClass> 复制到其他但将函数应用于 LINQ 中的属性

c# - 如何调试Web Service?

c# - 在动态范围内寻找局部最大值

multithreading - 在Apache托管的Delphi创建的ISAPI dll中获取当前上下文ID

c# - 当我坐在 Console.ReadLine() 上时,委托(delegate)会运行吗?