如何使用C#</t>从List <t> .AsParallel()。ForAll()中断

时间:2013-07-26 14:37:38

标签: 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();
    }
}    

}

此致 斯利拉姆

1 个答案:

答案 0 :(得分:4)

我相信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()进行类似任务的操作,Break()用于类似First的操作。

在微软的articles on parallel programming with .NET 4中有一篇关于这个主题的好文章,名为“何时为每个或PLINQ使用并行?”