我正在使用 BackgroundWorker
更新 ObservableCollection
但它给出了这个错误:
"This type of
CollectionView
does not support changes to itsSourceCollection
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/