Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what conditions can TryDequeue and similar System.Collections.Concurrent collection methods fail

I have recently noticed that inside the collection objects contained in System.Collections.Concurrent namespace it is common to see Collection.TrySomeAction() rather then Collection.SomeAction().

What is the cause of this? I assume it has something to do with locking?

So I am wondering under what conditions could an attempt to (for example) Dequeue an item from a stack, queue, bag etc.. fail?

like image 461
Maxim Gershkovich Avatar asked Apr 13 '11 06:04

Maxim Gershkovich


1 Answers

Collections in System.Collections.Concurrent namespace are considered to be thread-safe, so it is possible to use them to write multi-threaded programs that share data between threads.

Before .NET 4, you had to provide your own synchronization mechanisms if multiple threads might be accessing a single shared collection. You had to lock the collection each time you modified its elements. You also might need to lock the collection each time you accessed (or enumerated) it. That’s for the simplest of multi-threaded scenarios. Some applications would create background threads that delivered results to a shared collection over time. Another thread would read and process those results. You needed to implement your own message passing scheme between threads to notify each other when new results were available, and when those new results had been consumed. The classes and interfaces in System.Collections.Concurrent provide a consistent implementation for those and other common multi-threaded programming problems involving shared data across threads in lock-free way.

Try<something> has semantics - try to do that action and return operation result. DoThat semantics usually use exception thrown mechanics to indicate error which can be not efficient. As examples there they can return false,

  • if you try add new element, you might already have it in ConcurentDictionary;
  • if you try to get element from collection, it might not exists there;
  • if you try to update element there are can be more recent element already, so method ensures it updates only element which intended to update.

Try to read:

  • Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4 - best to start;
  • Parallel Programming in the .NET Framework;
  • read articles on Concurrency
  • Thread-safe Collections in .NET Framework 4 and Their Performance Characteristics
like image 158
Nick Martyshchenko Avatar answered Oct 28 '22 17:10

Nick Martyshchenko