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)
{
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
}
source
share