4

我正在开发处理大量文本数据收集单词出现统计信息的应用程序(请参阅:源代码词云)。

这是我的代码的简化核心正在做什么。

  1. 枚举所有带有 *.txt 扩展名的文件。
  2. 枚举每个文本文件中的单词。
  3. 按单词分组并计算出现次数。
  4. 按出现次数排序。
  5. 输出前 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();
                }
            }
        }
    }
}
4

3 回答 3

3

正如 Jon 所说,您需要在后台线程上启动 PLINQ 操作。这样,用户界面在等待操作完成时不会挂起(因此可以调用取消按钮的事件处理程序并调用Cancel取消令牌的方法)。PLINQ 查询会在令牌被取消时自动取消,因此您无需担心这一点。

这是执行此操作的一种方法:

private void buttonStart_Click(object sender, EventArgs e)
{
  // Starts a task that runs the operation (on background thread)
  // Note: I added 'ToList' so that the result is actually evaluated
  // and all results are stored in an in-memory data structure.
  var task = Task.Factory.StartNew(() =>
    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).ToList(), m_CancellationTokenSource.Token);

  // Specify what happens when the task completes
  // Use 'this.Invoke' to specify that the operation happens on GUI thread
  // (where you can safely access GUI elements of your WinForms app)
  task.ContinueWith(res => {
    this.Invoke(new Action(() => {
      try
      {
        foreach (Tuple<int, string> tuple in res.Result)
        {
          Console.WriteLine(tuple);
        }
      }
      catch (OperationCanceledException ex)
      {
          Console.WriteLine(ex.Message);
      }
    }));
  });
}
于 2011-08-02T18:14:06.957 回答
1

您当前正在UI 线程中迭代查询结果。即使查询是并行执行的,您仍在 UI 线程中迭代结果。这意味着 UI 线程忙于执行计算(或等待查询从其其他线程获取结果)以响应单击“取消”按钮。

您需要将遍历查询结果的工作放到后台线程上。

于 2011-08-02T17:32:23.400 回答
-1

我想我找到了一些优雅的解决方案,它更适合 LINQ / PLINQ 概念。

我正在声明一个扩展方法。

public static class ProcessWindowsMessagesExtension
{
    public static ParallelQuery<TSource> DoEvents<TSource>(this ParallelQuery<TSource> source)
    {
        return source.Select(
            item =>
            {
                Application.DoEvents();
                Thread.Yield();
                return item;
            });
    }
}

而不是将它添加到我想要响应的任何地方的查询中。

var result = Directory
            .EnumerateFiles(@"c:\temp", "*.txt", SearchOption.AllDirectories)
            .AsParallel()
            .WithCancellation(m_CancellationTokenSource.Token)
            .SelectMany(File.ReadLines)
            .DoEvents()
            .SelectMany(ReadWords)
            .GroupBy(word => word, (word, words) => new Tuple<int, string>(words.Count(), word))
            .OrderByDescending(occurrencesWordPair => occurrencesWordPair.Item1)
            .Take(20);

它工作正常!

有关更多信息和源代码,请参阅我的帖子:“如果可以,请取消我”或 WinForms 中的 PLINQ 可取消性和响应性

于 2011-08-03T05:19:35.493 回答