Getting ObservableCollection ThreadSafe
-
Hi guys! Experiencing something weird recently. Due to the fact, that my observable collection is the datacontext of my wpf app, I need to make sure, that every Thread is able to add Elements. Now the easy and working way is to add a
Dispatcher.Invoke(new Action(()=>{collection.Add(element}));
from every method being allowed to do so, which is kind of annoying. So I thought it would be a good idea to add the functionality to the observable collection itself. This is what I came up with:
class MElementsCollection :ObservableCollection<MElement>
{
#region Variables
private Dispatcher mainDipatcher;public Dispatcher MainDipatcher { get { if (mainDipatcher == null) mainDipatcher = App.MainDispatcher; return mainDipatcher; } } #endregion public void AddThreadSafe(MElement mElement) { if (Thread.CurrentThread != MainDipatcher.Thread) { MainDipatcher.Invoke(new Action(() => { this.Add(mElement); })); } else this.Add(mElement); } }
Now what's actually happening is, that by adding many items short one after another, not every item is added to the collection but just for example every second one. Can anyone please help me with this? As always, Thank you in advance
-
Hi guys! Experiencing something weird recently. Due to the fact, that my observable collection is the datacontext of my wpf app, I need to make sure, that every Thread is able to add Elements. Now the easy and working way is to add a
Dispatcher.Invoke(new Action(()=>{collection.Add(element}));
from every method being allowed to do so, which is kind of annoying. So I thought it would be a good idea to add the functionality to the observable collection itself. This is what I came up with:
class MElementsCollection :ObservableCollection<MElement>
{
#region Variables
private Dispatcher mainDipatcher;public Dispatcher MainDipatcher { get { if (mainDipatcher == null) mainDipatcher = App.MainDispatcher; return mainDipatcher; } } #endregion public void AddThreadSafe(MElement mElement) { if (Thread.CurrentThread != MainDipatcher.Thread) { MainDipatcher.Invoke(new Action(() => { this.Add(mElement); })); } else this.Add(mElement); } }
Now what's actually happening is, that by adding many items short one after another, not every item is added to the collection but just for example every second one. Can anyone please help me with this? As always, Thank you in advance