I need to make a ConcurrentBag as notifable. I need to know that is it safe? Code for the class is
public class NotifiableConcurrentBag<T> : ConcurrentBag<T>, INotifyCollectionChanged where T : class
{
public NotifiableConcurrentBag()
{
dispatcher = Dispatcher.CurrentDispatcher;
}
private Dispatcher dispatcher;
public event NotifyCollectionChangedEventHandler CollectionChanged;
public new void Add(T item)
{
base.Add(item);
if (CollectionChanged != null)
{
if (Thread.CurrentThread == dispatcher.Thread)
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
else
dispatcher.BeginInvoke((Action)(() =>
{
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
}
));
}
}
}
Thanks in advance.
You’re using method hiding:
public new void Add(T item) { ... }. So, when the client code gets the reference to the instance ofNotifiableConcurrentBag<T>asConcurrentBag<T>the wrong version ofAdd()(forConcurrentBag<T>) method will be called.I would like to suggest you extracting the
IConcurrentBag<T>interface.Then introduce new extended interface
INotifiableConcurrentBag<T>which actually supportsINotifyCollectionChangedinterface:After that just implement
NotifiableConcurrentBag<T>class (prefer composition over inheritance). Insert the notification logic instead of TODO markers.