Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't classes like BindingList or ObservableCollection thread-safe?

Tags:

Time and time again I find myself having to write thread-safe versions of BindingList and ObservableCollection because, when bound to UI, these controls cannot be changed from multiple threads. What I'm trying to understand is why this is the case - is it a design fault or is this behavior intentional?

like image 624
Dmitri Nesteruk Avatar asked Feb 09 '09 17:02

Dmitri Nesteruk


People also ask

What is the difference between ObservableCollection and BindingList?

Brief of Above: If a property of an item is changed in BindingList , the ListChanged event will give you complete details of property(in PropertyDescriptor) and ObservableCollection won't give you that. In fact ObservableCollection will not raise change event for a property changed in an item.


2 Answers

The problem is designing a thread safe collection is not simple. Sure it's simple enough to design a collection which can be modified/read from multiple threads without corrupting state. But it's much more difficult to design a collection that is usable given that it's updated from multiple threads. Take the following code as an example.

if ( myCollection.Count > 0 ) {   var x = myCollection[0]; } 

Assume that myCollection is a thread safe collection where adds and updates are guaranteed not to corrupt state. This code is not thread safe and is a race condition.

Why? Even though myCollection is safe, there is no guarantee that a change does not occur between the two method calls to myCollection: namedly Count and the indexer. Another thread can come in and remove all elements between these calls.

This type of problem makes using a collection of this type quite frankly a nightmare. You can't ever let the return value of one call influence a subsequent call on the collection.

EDIT

I expanded this discussion on a recent blog post: http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx

like image 103
JaredPar Avatar answered Oct 23 '22 11:10

JaredPar


To add a little to Jared's excellent answer: thread safety does not come for free. Many (most?) collections are only used within a single thread. Why should those collections have performance or functionality penalties to cope with the multi-threaded case?

like image 42
Jon Skeet Avatar answered Oct 23 '22 12:10

Jon Skeet