我编写了一个程序来测试 C# 4.0 中的并行编程。但是,有一个问题,我不知道为什么。
我写了一个方法
private void compute(int startValue, int endValue, ConcurrentBag<Pair> theList)
{
try
{
Task computation = Task.Factory.StartNew(() => { findFriendlyNumbers(startValue, endValue, theList, tokenSource.Token); }, tokenSource.Token);
Task.WaitAll(computation);
StringBuilder builder = new StringBuilder();
foreach (Pair p in theList)
{
builder.AppendLine(p.ToString());
}
this.textBlockResult.Dispatcher.Invoke(new Action(() =>
{
this.textBlockResult.Text = builder.ToString();
this.progressBar1.Visibility = System.Windows.Visibility.Hidden;
}));
}
catch (AggregateException aEx)
{
MessageBox.Show("Entering"); //For debug, but never runs
aEx.Handle(handleCancelling);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
它在单独的线程(UI线程除外)上运行。
和功能(简化)
private void findFriendlyNumbers(int start, int end, ConcurrentBag<Pair> list, CancellationToken token)
{
//some initialization and computation
for (int i = start; i <= end; i++)
{
//check whether it's cancelled
token.ThrowIfCancellationRequested();
//some computation
}
}
问题是,当tokenSource被取消时,会出现“OperationCanceledException is nothandled by user code”的错误,就好像catch块不存在一样。我不知道为什么,因为我的代码类似于教科书和 MSDN 中的代码。
谢谢你。
编辑:实际上我在不到一个月前写了一个类似的程序,那时一切都很好。今天我再次尝试运行它,同样的问题发生了。我在完成程序后安装了 Microsoft Visual Web Developer 2010 Express,不知道是不是这个原因。我不明白,相同的代码,不同的结果。
编辑:我想到了这个问题,发现哪里错了。过去,我使用“不调试运行”,而现在使用调试。在不调试的情况下运行可以解决问题。如果有人告诉我为什么调试与“无调试运行”不同,我将不胜感激。