"why aren't classes like bindinglist or observablecollection thread-safe?" Code Answer


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.


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

By Tina Vall on March 15 2022

Answers related to “why aren't classes like bindinglist or observablecollection thread-safe?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.