c# - 优化 Parallel.For 的性能

标签 c# .net

我已将代码中的 for 循环替换为 Parallel.For。性能提升非常棒(1/3 的运行时间)。我尝试使用数组来解释共享资源以收集结果代码。然后我在 Parallel.For 之外处理数组。这是最有效的方法还是即使没有迭代可以共享相同的循环索引,阻塞仍然会发生? CompareExchange 会表现得更好吗?

int[] pageResults = new int[arrCounter];
Parallel.For(0, arrCounter, i =>
{
   AlertToQueueInput input = new AlertToQueueInput();
   input.Message = Messages[i];

   pageResults[i] = scCommunication.AlertToQueue(input).ReturnCode;
});

foreach (int r in pageResults)
{
    if (r != 0 && outputPC.ReturnCode == 0) outputPC.ReturnCode = r;
}

最佳答案

这取决于您在主循环中是否有任何(有值(value)的)副作用。

outputPC.ReturnCode 是唯一的结果时,您可以使用 PLINQ:

outputPC.ReturnCode = Messages
    .AsParallel()
    .Select(msg =>    
    {
       AlertToQueueInput input = new AlertToQueueInput();
       input.Message = msg;        
       return scCommunication.AlertToQueue(input).ReturnCode;
    })
    .FirstOrDefault(r => r != 0);

这假定 scCommunication.AlertToQueue() 是线程安全的,并且您不想在第一个错误后为剩余的项目调用它。

请注意,PLinq 中的 FirstOrDefault() 仅有效 in Framework 4.5 and later .

关于c# - 优化 Parallel.For 的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30346774/

相关文章:

c# - 给定一个长度为 n 的列表,使用 C# 选择 k 个随机元素

C# 从 float 变量中获取数字

c# - 我应该默认推荐密封类吗?

C# toUpper 用于没有大写的语言

.net - Windows Identity Foundation - 第三方安全 token 服务器

.net - 为什么 Visual Studio 2015/2017/2019 测试运行程序没有发现我的 xUnit v2 测试

c# - 是否可以在已经创建的实例上直接调用构造函数?

c# - 在提示用户提及缺少的实体后,我如何使用 luis 操作绑定(bind)来触发意图

c# - 如何添加调试代码? (应该去Debug,不应该去Release)

c# - 在 C# 中解析带有标题的 CSV 文件