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.
The methods and properties of the
ConcurrentDictionarythemself are completely thread safe:http://msdn.microsoft.com/en-us/library/dd287191.aspx
This includes the Count property:
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
Taskobject and trying to run theExecutemethod on it. If you’d like serialised (locked) access to each individual task for theExecutemethod, then I suggest having a locking object insideTaskand locking when runningExecute: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.