c# - 如何尽可能快地同时填写多个列表?
问题描述
任何人都可以在最佳实践控制台应用程序示例中向我展示如何尽可能快地同时填充多个(例如 10 个具有 5k 随机数的列表)(与最大 CPU 消耗并行),并在每个列表填充 5k 后添加它号码排队?
解决方案
让我们实现(以线程安全的方式)列表创建:
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)));
推荐阅读
- c# - JSON:API 规范与使用 NewtonSoft 序列化对象
- c++ - 调用重载的构造函数会产生歧义错误 C++
- git - 从 Jenkins 运行 Katalon Studio 时构建失败
- c++ - 具有指针和节点嵌套类的树结构中的内存泄漏
- python - 在python的一行中声明多个变量
- flutter - 在页面转换期间,我的 BottomNavigationBar 如何漂浮在英雄小部件上方?
- ios - 应用程序因 iOS 13.2 中的 cpu 使用而终止
- javascript - 如何在 Laravel 中使用 JQuery / JavaScript 检查复选框
- reactjs - Electron setSize 方法和 ReactJS
- html - 滚动上的“位置:固定”图像