【发布时间】:2018-05-17 16:05:39
【问题描述】:
我需要帮助才能将此 for 循环转换为并行 forloop。
public void spellchecker()
{
Invoke(new MethodInvoker(delegate ()
{
using (Hunspell hunspell = new Hunspell("en_us.aff", "en_US.dic"))
{
foreach (Match match in Regex.Matches(GetRichTextBox().Text, @"\w+"))
{
string word = match.Value;
Font fnt = GetRichTextBox().Font;
Color color;
if (!hunspell.Spell(word))
{
fnt = new Font(fnt.FontFamily, fnt.Size, FontStyle.Underline);
color = Color.Red;
}
else
{
fnt = new Font(fnt.FontFamily, fnt.Size, FontStyle.Regular);
color = Color.Black;
}
GetRichTextBox().Select(match.Index, match.Length); // Selecting the matching word.
GetRichTextBox().SelectionColor = color;
GetRichTextBox().SelectionStart = GetRichTextBox().TextLength; // Resetting the selection.
GetRichTextBox().SelectionLength = 0;
}
}
}));
}
这是我尝试实现并行 for 循环时的实现。我不断收到一条错误消息,提示“无法从使用情况中推断出“Arguments for method'Parallel.ForEach<TSource>(IEnumereable<TSourcce>,Action<TSource>)'”
Parallel.ForEach(Regex.Matches(GetRichTextBox().Text, @"\w+"), match => {
string word = match.Value;
Font fnt = GetRichTextBox().Font;
Color color;
if (!hunspell.Spell(word))
{
fnt = new Font(fnt.FontFamily, fnt.Size, FontStyle.Underline);
color = Color.Red;
}
else
{
fnt = new Font(fnt.FontFamily, fnt.Size, FontStyle.Regular);
color = Color.Black;
}
GetRichTextBox().Select(match.Index, match.Length); // Selecting the matching word.
GetRichTextBox().SelectionColor = color;
GetRichTextBox().SelectionStart = GetRichTextBox().TextLength; // Resetting the selection.
GetRichTextBox().SelectionLength = 0;
});
【问题讨论】:
-
尝试
GetRichTextBox<String>()并将 lambda 转换为Action<String>
标签: c# task-parallel-library parallel.foreach