I have a WCF service in IIS App pool. Method of WCF service receives some data in JSON, like {"object": "someobject", "payload": [int key]}.
For each request I running new thread to work with key.
Key is adding to ConcurrentDictionary and locks value of ConcurrentDictionary.
Purpose of this is: only one examplar of key can run one time, example:
Thread 1-Running with key 1
Thread 2-Running with key 2
Thread 3-Waiting lock in Thread 1
But when I remove key from ConcurrentDictionary, another thread already get the value by key and works with it. How to avoid this?
Example of thread handler near
static ConcurrentDictionary<string, object> taskDictionary=new ConcurrentDictionary<string, object>();
static void ThreadHandler(int key)
{
try
{
var lockElem=taskDictionary.GetOrAdd(key, new object());
//Thread 3 get value by key 1 here and waits here
lock(lockElem)
{
taskDictionary.TryRemove(key, out _);
// but Thread 1 removes value by key 1 here
//and Thread 4 can add value in Dictionary with same key (key 1)
}
}
finally
{
}
}
Problem is in this case: Thread 1 uses GetOrAdd, then lock value, then TryRemove. In this time Thread 3. uses GetOrAdd, taking value, but waiting lock from Thread 1. When lock from Thread 1 releases, Thread 3 lock removed value. In this time Thread 4 uses GetOrAdd, and creating new dictionary element (which not match with value taken by Thread 3). And we have 2 threads (Thread 3 and Thread 4) which working with same key.