我有一个字符串的列表,如果我运行拼写检查使用NHunspell顺序方式,然后一切工作正常;但如果我使用的Parallel.For循环对列表中的应用程序停止运行在中间(一些地址冲突错误)Parallel.For循环拼写检查使用NHunspell和C#
public static bool IsSpellingRight(string inputword, byte[] frDic, byte[] frAff, byte[] enDic, byte[] enAff)
{
if (inputword.Length != 0)
{
bool correct;
if (IsEnglish(inputword))
{
using (var hunspell = new Hunspell(enAff, enDic))
{
correct = hunspell.Spell(inputword);
}
}
else
{
using (var hunspell = new Hunspell(frAff, frDic))
{
correct = hunspell.Spell(inputword);
}
}
return correct ;
}
return false;
}
编辑:
var tokenSource = new CancellationTokenSource();
CancellationToken ct = tokenSource.Token;
var poptions = new ParallelOptions();
// Keep one core/CPU free...
poptions.MaxDegreeOfParallelism = Environment.ProcessorCount - 1;
Task task = Task.Factory.StartNew(delegate
{
Parallel.For(0, total, poptions, i =>
{
if (words[i] != "")
{
_totalWords++;
if (IsSpellingRight(words[i],dictFileBytes,
affFileBytes,dictFileBytesE,affFileBytesE))
{
// do something
}
else
{
BeginInvoke((Action) (() =>
{
//do something on UI thread
}));
}
}
});
}, tokenSource.Token);
task.ContinueWith((t) => BeginInvoke((Action) (() =>
{
MessaageBox.Show("Done");
})));
哪里列表和你谈论的循环?更有可能的是,当你从多个线程使用列表时,你只是搞砸了一些东西。 – Tarec
该列表只是一个由RichTextBox文本构建的单词的标记化列表 – jeff
我不熟悉Hunspell类,但只需键入'correct = true;'或'false',运行它,然后查看是否问题在于你的方法或你的Parallel.For循环。在你粘贴的代码中我没有看到任何错误,除非Hunspell是一个单例 - 那么它显然意味着你不能以这种方式使用它。 – Tarec