some questions around the use of ConcurrentDictionary some questions around the use of ConcurrentDictionary multithreading multithreading

some questions around the use of ConcurrentDictionary


The methods and properties of the ConcurrentDictionary themself are completely thread safe:

http://msdn.microsoft.com/en-us/library/dd287191.aspx

Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.

This includes the Count property:

Count has snapshot semantics and represents the number of items in the ConcurrentDictionary at the moment when Count was accessed.

However this does not mean that the objects held inside the dictionary are themselves thread safe. That is, there is nothing stopping two threads from accessing the same Task object and trying to run the Execute method on it. If you'd like serialised (locked) access to each individual task for the Execute method, then I suggest having a locking object inside Task and locking when running Execute:

public class Task{    private object _locker = new object();    public void Execute()    {        lock (_locker) {           // code here        }    }}

This ensures that at least every individual task doesn't have multiple threads running Execute. I'm guessing this is what you're after from the context of the question and the names of the classes and methods.


All methods of ConcurrentDictionary are safe to be called from multiple threads.

It does not guarantees that other parts of your program need no synchronization as you may need to use locks to access other object/multiple objects at the same time.

I.e. your sample code does lock for both retrieving a task and executing it. It shows an example of locking to access multiple object atomically.

Side note: you should review your lock for task.Execute() as it prohibits other threads to execute task in parallel. It may be what you want to achieve, but in this case using ConcurrentDictionary may be overkill.