c#-4.0 - 如何使用 C# 从 List<T>.AsParallel().ForAll() 中断

标签 c#-4.0 plinq

我正在使用 List.AsParallel().ForAll() PLINQ 实现。在循环内部,如果我发现条件成功,我希望循环立即跳出 ForAll() 循环。我怎样才能实现它?

这是示例代码。

using System;
using System.Collections.Generic;
using System.Linq;

namespace Basics
{
class Program
{
    class Family
    {
        public int SNo { get; set; }
        public string Name { get; set; }
    }

    static List<Family> families = null;
    static Program()
    {
        families = new List<Family>()
        {
            new Family(){SNo = 10, Name="Richard"},
            new Family(){SNo = 33, Name="Xio Fung"},
            new Family(){SNo = 10, Name="Sean"},
            new Family(){SNo = 10, Name="Andrea"},
            new Family(){SNo = 20, Name="Bjorn"},
            new Family(){SNo = 20, Name="Isabella"},
            new Family(){SNo = 35, Name="Michael"},
            new Family(){SNo = 35, Name="Marie"}
        };
    }

    private static void Main()
    {
        Dictionary<int, List<Family>> theFamily = new Dictionary<int, List<Family>>();
        var groupedFamilies = families.GroupBy(family => family.SNo);

        groupedFamilies.AsParallel().ForAll(groupedFamily =>
        {
            int groupedFamilyCount = groupedFamily.Count();
            if (groupedFamilyCount == 1)
            {
                Console.WriteLine(groupedFamily.FirstOrDefault().Name);     
                // break; <-- I want to break if I find the count = 1
            }
        });                                 
        Console.ReadLine();
    }
}    

问候, 斯里拉姆

最佳答案

我相信 Parallel.ForEach 会起作用:

Parallel.ForEach(groupedFamilies.AsParallel(), (groupedFamily, loopState) =>
            {
                int groupedFamilyCount = groupedFamily.Count();
                if (groupedFamilyCount == 1)
                {
                    Console.WriteLine(groupedFamily.FirstOrDefault().Name);
                    loopState.Stop(); // break if I find the count = 1

                }
            });

根据您的用例,您可能需要 loopState.Break。使用 Stop() 进行类似 Any 的操作,使用 Break() 进行类似 First 的操作。

Microsoft 的 articles on parallel programming with .NET 4 中有一篇关于该主题的好文章称为“何时为每个或 PLINQ 使用并行?”

关于c#-4.0 - 如何使用 C# 从 List<T>.AsParallel().ForAll() 中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17884253/

相关文章:

c# - 相当于 do() while{} 在并行

javascript - 使用 AJAX 发送到 MVC 中的 Controller 时,嵌套的 javascript 对象属性为 null

.net - 我自己的托管类型作为 C++/CLI 类库中的 arg : CS0570: is not supported by the language

c# - `Dynamic` 到静态类转换器。它存在吗?

c# - 在 C# 中创建可重用代码模块(例如 C++ 样式类、 header )

c#-4.0 - 带有剑道网格的复选框列

c# - 使用 AsSequential 以保持顺序

c# - Plinq 里面的 Plinq?

c# - 使用 PLINQ Extensions 时,线程标识是否被转移?

c# - PLINQ 查询中的评估顺序是什么?