线程安全锁字典ConcurrentDictionary

单线程情况下:

ConcurrentDictionary的写操作比使用锁的字典Dictionary要慢得多,而读操作要快一些。因此如果对字典需要大量的线程安全的读操作,ConcurrentDictionary性能比较好。

使用单线程时,并发字典ConcurrentDictionary性能不及Dictionary,但是扩展到5到6个线程,并发字典性能会更好。

class Program    {       

 const string Item = "Dictionary item";       

 public static string CurrentItem;      

  static void Main(string[] args)    

    {                   

        var concurrentDictionary = new ConcurrentDictionary();//线程安全集合                

        var dictionary = new Dictionary();//字典集合

        var sw = new Stopwatch();

        sw.Start();

for (int i = 0; i < 1000000; i++)

   {

      lock (dictionary)

      {

   dictionary[i] = Item;

      }

 }

sw.Stop();

Console.WriteLine("Writing to dictionary with a lock:{0}",sw.ElapsedMilliseconds);

sw.Restart();

for (int i = 0; i < 1000000; i++)

{

concurrentDictionary[i] = Item;

}

sw.Stop();

Console.WriteLine("Writing to concurrent with a lock:{0}", sw.ElapsedMilliseconds);

sw.Restart();

for (int i = 0; i < 1000000; i++)

{

lock (dictionary)

{

CurrentItem = dictionary[i];

}

}

sw.Stop();

Console.WriteLine("reading to dictionary with a lock:{0}", sw.ElapsedMilliseconds);

sw.Restart();

for (int i = 0; i < 1000000; i++)

{

CurrentItem = concurrentDictionary[i];

}

sw.Stop();

Console.WriteLine("reading to concurrent with a lock:{0}", sw.ElapsedMilliseconds);

Console.ReadKey();

}

}


你可能感兴趣的:(线程安全锁字典ConcurrentDictionary)