Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there no concurrent collections in C#?

I am trying to get an overview of the thread safety theory behind the collections in C#.

Why are there no concurrent collections as there are in Java? (java docs). Some collections appear thread safe but it is not clear to me what the position is for example with regard to:

  • compound operations,
  • safety of using iterators,
  • write operations

I do not want to reinvent the wheel! (I am not a multi-threading guru and am definitely not underestimating how hard this would be anyway).

I hope the community can help.

like image 884
Andrew Avatar asked Dec 22 '09 13:12

Andrew


1 Answers

.NET has had relatively "low level" concurrency support until now - but .NET 4.0 introduces the System.Collections.Concurrent namespace which contains various collections which are safe and useful.

Andrew's answer is entirely correct in terms of how to deal with collections before .NET 4.0 of course - and for most uses I'd just lock appropriately when accessing a "normal" shared collection. The concurrent collections, however, make it easy to use a producer/consumer queue, etc.

like image 195
Jon Skeet Avatar answered Sep 21 '22 00:09

Jon Skeet