假设我们有两个线程和一个集合:
ConcurrentDictionary<int, object[]> lists = new ConcurrentDictionary<int, object[]>();
1)一个线程处理集合中的元素,然后从集合中删除元素
foreach(object[] elem in lists.Values)
{
//do somethind
lists.TryRemove(key, out vals);
}
2)第二个线程将元素添加到集合中,然后它需要能够检查元素状态:
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
}