0

I have an Observable collection object whose value I am updating from my code. This collection is bound two way to a data grid. Now, is this collection thread safe - that is if I try to modify the value of the collection from the code and at the same time the user tries to modify it(as a result of editing the data grid), would the program throw an exception? If yes, can you please explain how to avoid this?

Thanks...

Kevek
  • 2,534
  • 5
  • 18
  • 29
Manoj
  • 5,011
  • 12
  • 52
  • 76

1 Answers1

1

This looks like a duplicate here, and here but the short answer is that you're safe if you're modifying a property.

As you're working with a collection there's a bit more you need to do if you're trying to modify an ObservableCollection on multiple threads and not just the UI thread. This has been covered a lot, and you can check out at either this link or this one

However if you're doing your modifications within the UI thread, you are safe as this is what the ObservableCollection is intended for. The events will be created and handled on the UI theread as long as you are properly marshaling via Dispatcher.BeginInvoke().

Community
  • 1
  • 1
Kevek
  • 2,534
  • 5
  • 18
  • 29
  • I am using the Dispatcher.BeginInvoke method to update the observable collection in the UI thread. So is it like - when a user edits the data grid, a lock is obtained on the Observable collection and the method I am calling using Dispatcher.BeginInvoke will wait for it to complete? – Manoj Oct 03 '11 at 14:47
  • @Manoj as your marshaling your work onto the UI thread via Dispatcher.BeginInvoke you are fine. Problems **do** arise when you try to change the collection on a different thread, but I don't believe that's what you're doing. I am looking to confirm my understanding, but as far as I understand it, it's not a "lock" per se, but rather you are creating a NotifyCollectionChanged event that is added to a queue of such events that will read by the UI components that are bound, and will thus update themselves with the new contents of the collection – Kevek Oct 03 '11 at 15:17
  • @Manoj this convinces me that I am not crazy: "_When an ObservableCollection is modified, it raises an event. Events are handled synchronously. Event handlers respond on the same thread as the modification. The handler completes before the Add or Remove method returns. This means that you can’t modify an ObservableCollection in a background thread._" which comes from [this link](http://updatecontrols.net/doc/tips/common_mistakes_observablecollection) about three-quarters of the way down the page. – Kevek Oct 03 '11 at 15:25