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?
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,
ConcurentDictionary
;Try to read:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With