我正在开发处理大量文本数据收集单词出现统计信息的应用程序(请参阅:源代码词云)。
这是我的代码的简化核心正在做什么。
- 枚举所有带有 *.txt 扩展名的文件。
- 枚举每个文本文件中的单词。
- 按单词分组并计算出现次数。
- 按出现次数排序。
- 输出前 20 名。
LINQ 一切正常。迁移到 PLINQ 给我带来了显着的性能提升。但是......在长时间运行的查询期间的可取消性丢失了。
似乎 OrderBy 查询正在将数据同步回主线程,并且未处理 windows 消息。
在下面的示例中,我根据MSDN How to: Cancel a PLINQ Query 来演示我的取消实现,它不起作用:(
还有其他想法吗?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace PlinqCancelability
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
m_CancellationTokenSource = new CancellationTokenSource();
}
private readonly CancellationTokenSource m_CancellationTokenSource;
private void buttonStart_Click(object sender, EventArgs e)
{
var result = Directory
.EnumerateFiles(@"c:\temp", "*.txt", SearchOption.AllDirectories)
.AsParallel()
.WithCancellation(m_CancellationTokenSource.Token)
.SelectMany(File.ReadLines)
.SelectMany(ReadWords)
.GroupBy(word => word, (word, words) => new Tuple<int, string>(words.Count(), word))
.OrderByDescending(occurrencesWordPair => occurrencesWordPair.Item1)
.Take(20);
try
{
foreach (Tuple<int, string> tuple in result)
{
Console.WriteLine(tuple);
}
}
catch (OperationCanceledException ex)
{
Console.WriteLine(ex.Message);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
m_CancellationTokenSource.Cancel();
}
private static IEnumerable<string> ReadWords(string line)
{
StringBuilder word = new StringBuilder();
foreach (char ch in line)
{
if (char.IsLetter(ch))
{
word.Append(ch);
}
else
{
if (word.Length != 0) continue;
yield return word.ToString();
word.Clear();
}
}
}
}
}