I have multiple queues that are being accessed by multiple threads. To achieve thread-safety, I did the following:
private static Dictionary<string, Queue<string>> MyQueues = new Dictionary<string, Queue<string>>();
public static string GetNextQueueElementForKey(string key)
{
string res = string.Empty;
if (MyQueues.Keys.Contains(key))
{
Queue<string> queue = MyQueues[key];
lock (queue)
{
if (queue.Count() > 0)
{
res = queue.Dequeue();
}
}
}
return res;
}
I could also lock MyQueues
, but then I would lock more than necessary. So my question is, if locking an object contained in a dictionary is going to work - assuming that a key's value (the queue) is never changed.