首页 > 解决方案 > 如何尽可能快地同时填写多个列表?

问题描述

任何人都可以在最佳实践控制台应用程序示例中向我展示如何尽可能快地同时填充多个(例如 10 个具有 5k 随机数的列表)(与最大 CPU 消耗并行),并在每个列表填充 5k 后添加它号码排队?

标签: c#listparallel-processing

解决方案


让我们实现(以线程安全的方式)列表创建:

   using System.Collections.Concurrent;
   using System.Security.Cryptography;
   using System.Threading;

   ... 

   private static List<int> CreateAndFill(int count) {
     // Random is not thread safe; so we have to use local variable
     // when using local variable, we have to provide entropy
     // which we can get from RNGCryptoServiceProvider
     Random random; 

     using (var provider = new RNGCryptoServiceProvider()) {
       byte[] seedData = new byte[sizeof(int)];
       provider.GetBytes(seedData);

       random = new Random(BitConverter.ToInt32(seedData, 0));
     }

     List<int> result = new List<int>(count);

     for (int i = result.Count - 1; i >= 0; --i)
       result.Add(random.Next(100)); //TODO: put required range here

     return result; 
   } 

然后你可以尝试Parallel.For

   ConcurrentQueue<List<int>> queue = new ConcurrentQueue<List<int>>();

   Parallel.For(0, 10, i => queue.Enqueue(CreateAndFill(5000))); 

推荐阅读