0

我目前正在使用 NHunspell 在 WPF 中实现自定义拼写检查,因为 .Net Framework 的本机解决方案不符合我的需求。但是我在检查大文本中的单词时遇到了麻烦,例如带有 10 个段落的 Lorem Ipsum,因为我需要检查每个单词,看看它是否包含在 Hunspell 使用的字典中,如果没有,我需要在那个词下划线。

我有这个当前的方法,每次 KeyUp 是退格键或空格键时都会检查所有文本。

var textRange = new TextRange(SpellCheckRichTextBox.Document.ContentStart, 
SpellCheckRichTextBox.Document.ContentEnd);
        textRange.ApplyPropertyValue(Inline.TextDecorationsProperty, null);
        _viewModel.Text = textRange.Text;
        var zzz = _viewModel.Text.Split(' ');
        var kfeofe = zzz.Where(x => _viewModel.MisspelledWords.Contains(x));
        foreach (var item in kfeofe)
        {
            TextPointer current = textRange.Start.GetInsertionPosition(LogicalDirection.Forward);

            while (current != null)
            {
                string textInRun = current.GetTextInRun(LogicalDirection.Forward);
                if (!string.IsNullOrWhiteSpace(textInRun))
                {
                    int index = textInRun.IndexOf(item.ToString());
                    if (index != -1)
                    {
                        TextPointer selectionStart = current.GetPositionAtOffset(index, LogicalDirection.Forward);
                        TextPointer selectionEnd = selectionStart.GetPositionAtOffset(item.ToString().Length, LogicalDirection.Forward);
                        TextRange selection = new TextRange(selectionStart, selectionEnd);

                        selection.ApplyPropertyValue(Inline.TextDecorationsProperty, TextDecorations.Underline);
                    }
                }
                current = current.GetNextContextPosition(LogicalDirection.Forward);
            }

        }

但是,我认为我需要一个异步解决方案,所以它不会阻塞我的主线程和用户的输入。- 从理论上讲,如果用户在没有输入的情况下花费超过 2 秒的时间,然后将选中的 TextRange 返回到我的 RichTextBox (SpellCheckRichTextBox),我正在考虑运行并行线程。

有人可以提出任何解决方案,以便在处理大文本时降低验证速度吗?我真的坚持这一点,任何帮助将不胜感激。提前致谢!

4

1 回答 1

1

第一个改进是

zzz.AsParallel().Where(x => _viewModel.MisspelledWords.Contains(x)).ToList();

这显然假设你.MisspelledWords.Contains(x)可以并行完成的事情。它可能已经是ConcurrentDictionary了。

您收集了拼写错误的单词这一事实让我相信您已经解析过一次文本。那么为什么要解析两次呢?为什么你不能把这两个通行证结合起来?那将是另一种可能的优化。

是的,当用户停止输入时,在另一个线程中执行所有这些操作会更好。

于 2017-10-19T13:48:08.540 回答