up谁来接分。自己测试了一下,遍历没有问题。 我的测试代码: ConcurrentDictionary<int, int> cities = new ConcurrentDictionary<int, int>(); Parallel.Invoke( () => { int i = 0; while (true) { int j = i + 10; for (; i < j; i++) { if (cities.TryAdd(i, i)) Console.WriteLine("++Add {0}", i); Thread.Sleep(10); } i -= 5; j = i + 5; for (; i < j; i++) { int t; if (cities.TryRemove(i, out t)) Console.WriteLine("--Remove {0}", i); Thread.Sleep(10); } } }, () => { while (true) { Console.WriteLine("***********************************************************"); foreach (var item in cities) { Console.WriteLine("<<Output {0}", item.Value); Thread.Sleep(5); } Thread.Sleep(1000); } });
我的测试代码:
ConcurrentDictionary<int, int> cities = new ConcurrentDictionary<int, int>(); Parallel.Invoke(
() =>
{
int i = 0;
while (true)
{
int j = i + 10;
for (; i < j; i++)
{
if (cities.TryAdd(i, i))
Console.WriteLine("++Add {0}", i);
Thread.Sleep(10);
}
i -= 5;
j = i + 5;
for (; i < j; i++)
{
int t;
if (cities.TryRemove(i, out t))
Console.WriteLine("--Remove {0}", i);
Thread.Sleep(10);
}
}
},
() =>
{
while (true)
{
Console.WriteLine("***********************************************************");
foreach (var item in cities)
{
Console.WriteLine("<<Output {0}", item.Value);
Thread.Sleep(5);
}
Thread.Sleep(1000);
}
});
{
//其他代码
}如果下面这种形式,迭代的结果将是MyDictionary某一时刻的快照,不包含脏数据 foreach (var item in MyDictionary.ToArray())
{
//其他代码
}同时,ConcurrentDictionary 的Count, Keys, Values 属性也是某一时刻的快照