Pregunta

I am currently writing a C# application. I am new to using a ConcurrentDictionary so have some questions around its thread safety. Firstly, this is my dictionary:

    /// <summary>
    /// A dictionary of all the tasks scheduled
    /// </summary>
    private ConcurrentDictionary<string, ITask> tasks;

I instantiate this in my class and use it to track all of my objects that implement ITask. I want ensure my setup will work correctly in a multi threaded environment.

If multiple threads want to get the count of the number of items in the ConcurrentDictionary, do I need to lock it?

If I want to get a particular key from the dictionary, get the object of that key and call a method on it, do I need to lock it? eg:

    /// <summary>
    /// Runs a specific task.
    /// </summary>
    /// <param name="name">Task name.</param>
    public void Run(string name)
    {
        lock (this.syncObject)
        {
            var task = this.tasks[name] as ITask;
            if (task != null)
            {
                task.Execute();
            }
        }
    }

Keeping mind multiple threads could call the Run method looking to call the Execute method of ITask. My aim is to have everything thread safe and as performant as possible.

¿Fue útil?

Solución

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.

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top