string res = "";
var concurrentDictionary = new ConcurrentDictionary<int, string>();
var dictionary = new Dictionary<int, string>();
dictionary.TryAdd(1, "aa");
concurrentDictionary.TryAdd(1,"");
var sw = new Stopwatch();
sw.Start();
Parallel.For(0, 1000000, i =>//Parallel使用并行循环
{
lock (dictionary)
{
dictionary[i] = new Random().Next(1000, 9999).ToString();
}
});
sw.Stop();
Console.WriteLine("加锁写入dictionary {0}", sw.Elapsed);
//wrinting to dictionary with a lock: 00:00:00.0633939
sw.Restart();
Parallel.For(0, 1000000, i =>
{
concurrentDictionary[i] = new Random().Next(1000, 9999).ToString();
});
sw.Stop();
Console.WriteLine("concurrentdictionary写入时长 : {0}", sw.Elapsed);
sw.Restart();
Parallel.For(0, 1000000, i =>
{
lock (dictionary)
{
res = dictionary[i];
}
});
sw.Stop();
Console.WriteLine("读取dictionary耗时: {0}", sw.Elapsed);
sw.Restart();
Parallel.For(0, 1000000, i =>
{
res = concurrentDictionary[i];
});
sw.Stop();
Console.WriteLine("读取concurrentdictionary耗时: {0}", sw.Elapsed);
Console.ReadLine();
文档更新时间: 2022-12-15 11:34 作者:admin