Skip to main content
 首页 » 编程设计

c#之这个 LinQ 语句可以运行多线程之使用更多的 cpu 内核

2024年02月13日14daizhj

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

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

        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

请您参考如下方法:

以下代码片段可以使用 Parallel Tasks Library's 执行该操作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. 
    });