2013-05-31 47 views
1

我已经写了下面的linq语句。但是由于线路太多,处理需要很长的时间。我的CPU有8个内核,但由于运行单线程只使用1个内核。这个LinQ语句可以运行多线程 - 使用更多的cpu核心

所以我很想知道这个最终版本能够在多线程中运行吗?

 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,netframework 4.5

+2

看着[PLINQ](http://msdn.microsoft.com/zh-cn/library/dd460688.aspx)?请注意,这无法保证让任何事情都能更快运行。 –

+0

@AdamHouldsworth还没有检查,但让我看看:) – MonsterMMORPG

+0

http://stackoverflow.com/questions/7582591/how-to-plinq-an-existing-linq-query-with-joins([了解加速在PLINQ中](http://msdn.microsoft.com/en-us/library/dd997399.aspx))查询的代价越高,PLINQ的候选人就越好。 –

回答

3

下面的代码片断可以使用Parallel Tasks Library'sParallel.ForEach方法执行该操作。下面的代码片段将你所拥有的'all-lines'文件中的每一行都分隔开,然后在每一行中搜索被禁止的单词。 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. 
    }); 
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

+1

这不是我,但你可能想要将'lstAllLines'变量重命名为'hashAllWords',以使代码更易于理解。 – Dirk

+0

@Dirk我只想保留OP的变量名称。毕竟,使用VS只是重构/重命名。 – I4V

+0

其实这不完全是我在做什么:)也我没有投票。我正在逐字检查,你正在检查文字级别。 – MonsterMMORPG