c# – ConcurrentDictionary和ConcurrentQueue的这种组合是线程安全的吗?

前端之家收集整理的这篇文章主要介绍了c# – ConcurrentDictionary和ConcurrentQueue的这种组合是线程安全的吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在以下代码中使用.NET 4中的ConcurrentDictionary和ConcurrentQueue类.

这段代码是线程安全的吗?如果没有,我怎样才能使它成为线程安全的?

  1. public class Page
  2. {
  3. public string Name {get; set; }
  4. }
  5.  
  6. public class PageQueue
  7. {
  8. private ConcurrentDictionary<int,ConcurrentQueue<Page>> pages =
  9. new ConcurrentDictionary<int,ConcurrentQueue<Page>>();
  10.  
  11. public void Add(int id,Page page)
  12. {
  13. if (!this.pages.ContainsKey(id))
  14. this.pages[id] = new ConcurrentQueue<Page>();
  15.  
  16. this.pages[id].Enqueue(page);
  17. }
  18.  
  19. public Page GetAndRemove(int id)
  20. {
  21. Page lp = null;
  22.  
  23. if(this.pages.ContainsKey(id))
  24. this.pages[id].TryDequeue(out lp);
  25.  
  26. return lp;
  27. }
  28. }

演示:

  1. public class Demo
  2. {
  3. public void RunAll()
  4. {
  5. for (int i = 0; i < 10; i++)
  6. Task.Factory.StartNew(() => Run());
  7. }
  8.  
  9. public void Run()
  10. {
  11. PageQueue pq = new PageQueue();
  12. pq.Add(1,new Page());
  13.  
  14. pq.GetAndRemove(1);
  15. }
  16. }

解决方法

正如@Femaref正确指出的那样,代码中存在一些缺陷.我建议你利用 ConcurrentDictionary<K,V>提供的许多方法使代码线程安全而不需要锁定语句:
  1. public class PageQueue
  2. {
  3. private ConcurrentDictionary<int,ConcurrentQueue<Page>>();
  4.  
  5. public void Enqueue(int id,Page page)
  6. {
  7. var queue = this.pages.GetOrAdd(id,_ => new ConcurrentQueue<Page>());
  8.  
  9. queue.Enqueue(page);
  10. }
  11.  
  12. public bool TryDequeue(int id,out Page page)
  13. {
  14. ConcurrentQueue<Page> queue;
  15.  
  16. if (this.pages.TryGetValue(id,out queue))
  17. {
  18. return queue.TryDequeue(out page);
  19. }
  20.  
  21. page = null;
  22. return false;
  23. }
  24. }

猜你在找的C#相关文章