在我编写的自定义集合类中考虑以下(简化)代码:
public class ObservableConcurrentCollection<T> : IObservableConcurrentCollection<T>
{
public ObservableConcurrentCollection( )
{
_context = Application.Current?.Dispatcher;
}
private void _notify() //This may be called from any thread
{
if (_context.Checkaccess())
{
_invokeCollectionChanged();
}
else
{
_context.InvokeAsync(() => _invokeCollectionChanged(),DispatcherPriority.Normal);
}
}
private void _invokeCollectionChanged() //This is only expected to be called from the main/UI thread
{
CollectionChanged?.Invoke(this,new NotifyCollectionChangedEventArgs(NotifyCollectionChangedaction.Reset));
}
}
引发事件时,我得到了臭名昭著的“此CollectionView类型不支持从与Dispatcher线程不同的线程对其SourceCollection进行的更改”异常。为什么? Checkaccess
不可靠吗?当异常触发时,Visual Studio会说我在主/ UI线程上...
有什么想法去哪里找?
编辑:问题是代码在99.99%的时间内运行良好,崩溃时很少执行一次。我已经在SO和其他地方经历了通用的同步机制,这似乎很好。
好像有某种比赛条件-但我不知道谁在跑步...