1

我写了下面的 linq 语句。但是由于行数太多,因此需要大量时间来处理。我的 cpu 有 8 个内核,但由于运行单线程而只使用 1 个内核。

所以我想知道这个最后的语句是否可以在多线程中运行?

        List<string> lstAllLines = File.ReadAllLines("AllLines.txt").ToList();
        List<string> lstBannedWords = File.ReadAllLines("allBaddWords.txt").
Select(s => s.ToLowerInvariant()).
Distinct().ToList();

我问的是下面那个。那条线可以多线程工作吗?

        List<string> lstFoundBannedWords = lstBannedWords.Where(s => lstAllLines.
SelectMany(ls => ls.ToLowerInvariant().Split(' ')).
Contains(s)).
        Distinct().ToList();

C# 5 , 网络框架 4.5

4

2 回答 2

5

以下代码片段可以使用并行任务库的 Parallel.ForEach方法执行该操作。下面的代码片段获取您拥有的“所有行”文件中的每一行,将其拆分为空格,然后在每一行中搜索禁用词。Parallel-ForEach 应该使用您机器处理器上的所有可用内核。希望这可以帮助。

System.Threading.Tasks.Parallel.ForEach(
    lstAllLines,
    line =>
    {
        var wordsInLine = line.ToLowerInvariant().Split(' ');
        var bannedWords = lstBannedWords.All(bannedWord => wordsInLine.Contains(bannedWord));
        // TODO: Add the banned word(s) in the line to a master list of banned words found.
    });
于 2013-05-31T14:48:14.320 回答
1

在诉诸于之前有性能改进的空间AsParallel

HashSet<string> lstAllLines = new HashSet<string>(
                                File.ReadAllLines("AllLines.txt")
                                    .SelectMany(ls => ls.ToLowerInvariant().Split(' ')));

List<string> lstBannedWords = File.ReadAllLines("allBaddWords.txt")
                                    .Select(s => s.ToLowerInvariant())
                                    .Distinct().ToList();

List<string> lstFoundBannedWords = lstBannedWords.Where(s => lstAllLines.Contains(s))
                                    .Distinct().ToList();

由于对 HasSet 的访问是O(1)并且lstBannedWords现在是较短的列表,因此您甚至可能不需要任何并行性 ( TotalSearchTime=lstBannedWords.Count*O(1))。最后,您始终可以选择AsParallel

于 2013-05-31T14:24:15.203 回答