I'm having trouble locking an item in a collection - in particular, ConcurrentDictionary.
I need to accept a message, look at this message in the dictionary, and then run a long scan. Since the program takes up a lot of memory, after scanning, objects return true if they believe that this is a good time to delete it (which I do by deleting it from the Dictionary). However, another thread may arrive at the same time and try to access the same object immediately after deletion. This is my first attempt:
string dictionaryKey = myMessage.someValue;
DictionaryObject currentObject = myConcurrentDictionary.GetOrAdd(dictionaryKey, new DictionaryObject());
lock (currentObject)
{
if (myConcurrentDictionary[dictonaryKey].scan(myMessage))
{
DictionaryObject temp;
if (!queuedMessages.TryRemove(ric, out temp))
throw new Exception("Was unable to delete a DictionaryObject that just reported it was ok to delete it");
}
}
- , , . , , Monitor.Enter Monitor.Exit, :
string dictionaryKey = myMessage.someValue;
Monitor.Enter(GetDictionaryLocker);
DictionaryObject currentObject = myConcurrentDictionary.GetOrAdd(dictionaryKey, new DictionaryObject());
lock (currentObject)
{
Monitor.Exit(GetDictionaryLocker);
if (myConcurrentDictionary[dictonaryKey].scan(myMessage))
{
DictionaryObject temp;
if (!queuedMessages.TryRemove(ric, out temp))
throw new Exception("Was unable to delete a DictionaryObject that just reported it was ok to delete it");
}
}
KeyNotFoundException .
- , , , , ? - concurrency !
,