I have an abstract class which has a Protected Method. I am using dictionary inside this method. And this class has 2 implementations. Both the classes call this protected method for
some operations. If both the implementations are running in different threads, is the dictionary inside the protected method thread safe?
Protected method is as below
protected Dictionary<string, string> GenerateParameterFromQueue()
{
Dictionary<string, string> parameters;
string queueInput = this._Queue.QueueInput;
string[] inputArray = Regex.Split(queueInput,Constants.KEY_DELIMITER);
parameters = inputArray.ToDictionary(s => s.Split(Convert.ToChar(Constants.KEY_EQUALITY))[0], s => s.Split(Convert.ToChar(Constants.KEY_EQUALITY))[1]);
return parameters;
}
Yes, since the dictionary in the method is created per thread inside the method itself, your use of the
Dictionaryis thread safe. Of course, that does not mean that any use of it outside the method after it has been returned is automatically thread safe.It’s only if two threads access/change a single
Dictionarythat you will have a problem. It has nothing to do with the method being protected.The thing I’d worry about in the method is the this._Queue variable though, since it’s shared between multiple threads and you’re not locking it, you need to make sure that it’s thread safe in itself.