我有以下测试:
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
IDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>(); // FAILS sometimes
// ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>(); // WORKS always
Parallel.For(0, 10, i => dictionary.TryAdd("x1", "y1"));
}
}
如果我在.NET FIDELL中运行它,有时会得到以下异常:
Unhandled exception. System.AggregateException: One or more errors occurred. (The key already existed in the dictionary)
System.ArgumentException: The key already existed in the dictionary.at System.Collections.Concurrent.ConcurrentDictionary`2.System.Collections.Generic.IDictionary<TKey,TValue>.Add(TKey key, TValue value)
at System.Collections.Generic.CollectionExtensions.TryAdd[TKey,TValue](IDictionary`2 dictionary, TKey key, TValue value)
at Program.<>c__DisplayClass0_0.b__0(Int32 i)
at System.Threading.Tasks.Parallel.<>c__DisplayClass19_0`2.b__1(RangeWorker& currentWorker, Int64 timeout, Boolean& replicationDelegateYieldedBeforeCompletion)
--- End of stack trace from previous location ---
at System.Threading.Tasks.Parallel.<>c__DisplayClass19_0`2.b__1(RangeWorker& currentWorker, Int64 timeout, Boolean& replicationDelegateYieldedBeforeCompletion)
at System.Threading.Tasks.TaskReplicator.Replica.Execute()
--- End of inner exception stack trace ---
然而,如果我不施展ConcurrentDictionary
,它似乎总是有效的.
到底怎么回事?