我在c#中使用任务并行库创建一个记事本应用程序。但是在输入大约2秒后,由于跨线程调用(拼写检查)或者有时UI冻结,我得到一个无效的操作异常好。有人可以告诉我一个更好的方法来调用我的GetRichTextbox方法。我觉得问题出在GetRichTextBox()方法的某个地方。
public RichTextBox GetRichTextBox()
{
Invoke(new MethodInvoker(delegate ()
{
RichTextBox rtb = null;
TabPage tp = tabControl1.SelectedTab;
if(tp!= null)
{
rtb = tp.Controls[0] as RichTextBox;
}
}));
return rtb;
}
public void spellchecker()
{
Invoke(new MethodInvoker(delegate ()
{
using (Hunspell hunspell = new Hunspell("en_us.aff", "en_US.dic"))
{
Parallel.ForEach(Regex.Matches(GetRichTextBox().Text, @"\w+").Cast<Match>(), 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().SelectionFont = fnt; // Changing its font
GetRichTextBox().SelectionColor = color;
GetRichTextBox().SelectionStart =
GetRichTextBox().TextLength; // Resetting the selection.
GetRichTextBox().SelectionLength = 0;
});
}
}));
}
private void newtab()
{
TabPage tp = new TabPage("New Doc");
rtb = new RichTextBox();
rtb.HideSelection = false;
rtb.TextChanged += (bs, be) =>
{
Parallel.Invoke(
() => spellchecker(),
() => wordCount());
};
rtb.Dock = DockStyle.Fill;
tp.Controls.Add(rtb);
tabControl1.TabPages.Add(tp);
}