在 INotifyCollectionChanged 的自定义实现上触发 CollectionChanged 事件时出现此异常:
PresentationFramework.dll 中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理
附加信息:集合更改事件中的“25”索引对于大小为“0”的集合无效。
XAML 数据网格作为 ItemsSource 绑定到集合。
如何避免这种异常的发生?
代码如下:
public class MultiThreadObservableCollection<T> : ObservableCollection<T>
{
private readonly object lockObject;
public MultiThreadObservableCollection()
{
lockObject = new object();
}
private NotifyCollectionChangedEventHandler myPropertyChangedDelegate;
public override event NotifyCollectionChangedEventHandler CollectionChanged
{
add
{
lock (this.lockObject)
{
myPropertyChangedDelegate += value;
}
}
remove
{
lock (this.lockObject)
{
myPropertyChangedDelegate -= value;
}
}
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
var eh = this.myPropertyChangedDelegate;
if (eh != null)
{
Dispatcher dispatcher;
lock (this.lockObject)
{
dispatcher = (from NotifyCollectionChangedEventHandler nh in eh.GetInvocationList()
let dpo = nh.Target as DispatcherObject
where dpo != null
select dpo.Dispatcher).FirstOrDefault();
}
if (dispatcher != null && dispatcher.CheckAccess() == false)
{
dispatcher.Invoke(DispatcherPriority.DataBind, (Action)(() => this.OnCollectionChanged(e)));
}
else
{
lock (this.lockObject)
{
foreach (NotifyCollectionChangedEventHandler nh in eh.GetInvocationList())
{
nh.Invoke(this, e);
}
}
}
}
}
错误发生在以下行:
nh.Invoke(this, e);
谢谢!