Check if an item exists in a collection in a multi-threaded application

Suppose we have two threads and a collection:

ConcurrentDictionary<int, object[]> lists = new ConcurrentDictionary<int, object[]>();

1) One thread processes items in the collection and then removes items from the collection

foreach(object[] elem in lists.Values)
{
    //do somethind
    lists.TryRemove(key, out vals);
}

2) The second stream adds elements to the collection, and then it should be able to check the status of the elements:

lists.Add(10, some_object);

...

if(lists.ContainsKey(10))
{

    //How can I be sure that at this moment element is still exists ?
    //Thread may be preempted after if() {} and second thread 
    //can remove object from collection
}
+4
source share
2 answers

You should use TryGetValue, as this ensures that the check / receive is atomic:

object[] val;
if(lists.TryGetValue(10, out val)) {
    // Here you have a reference to the object[], even if it has subsequently been removed
}

, object[] - , ConcurrentDictionary. (, , - , , TryGetValue.)

+5

, . , , .

// in thread 1
lock(COMMON_LOCK_OBJECT)
{
   foreach(object[] elem in lists.Values)
   {
     //do somethind
     lists.TryRemove(key, out vals);
   }

}

An 2:

lock(COMMON_LOCK_OBJECT)
{
    lists.Add(10, some_object);

    ...

    if(lists.ContainsKey(10))
    {

    }
}
0

All Articles