关键词搜索

源码搜索 ×
×

C# 并发安全集合ConcurrentBag取代List

发布2018-06-01浏览22551次

详情内容

List集合是非线程安全的,所以我们这里了解下安全集合ConcurrentBag。

控制台测试程序:

  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace MyConcurrent
  9. {
  10. class Program
  11. {
  12. /// <summary>
  13. /// ConcurrentBag并发安全集合
  14. /// </summary>
  15. public static void ConcurrentBagWithPallel()
  16. {
  17. ConcurrentBag<int> list = new ConcurrentBag<int>();
  18. Parallel.For(0, 10000, item =>
  19. {
  20. list.Add(item);
  21. });
  22. Console.WriteLine("ConcurrentBag's count is {0}", list.Count());
  23. int n = 0;
  24. foreach (int i in list)
  25. {
  26. if (n > 10)
  27. break;
  28. n++;
  29. Console.WriteLine("Item[{0}] = {1}", n, i);
  30. }
  31. Console.WriteLine("ConcurrentBag's max item is {0}", list.Max());
  32. }
  33.         /// <summary>
  34.         /// 函数入口
  35.         /// </summary>
  36.         /// <param name="args"></param>
  37.         static void Main(string[] args)
  38.         {
  39.             Console.WriteLine("ConcurrentBagWithPallel is runing" );
  40.             ConcurrentBagWithPallel();
  41.             Console.Read();
  42.         }
  43. }

参考地址:http://www.cnblogs.com/yunfeifei/p/3998783.html


相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载