0

我编写了一个程序来测试 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,不知道是不是这个原因。我不明白,相同的代码,不同的结果。

编辑:我想到了这个问题,发现哪里错了。过去,我使用“不调试运行”,而现在使用调试。在不调试的情况下运行可以解决问题。如果有人告诉我为什么调试与“无调试运行”不同,我将不胜感激。

4

1 回答 1

1

您正在将取消令牌传递给该TaskFactory.StartNew方法。这使它Task特别对待它:作为取消而不是错误的指示。

如果您不将令牌作为参数传递给TaskFactory.StartNew,那么它将被视为错误并被捕获。Task.IsCanceled如果您确实将其保留为参数,那么您需要使用而不是异常来检查取消。

旁注:最好不要用于Invoke同步到 UI 线程。我的博客上有一个正确执行 UI 进度更新的对象示例。Task

于 2010-08-23T03:01:30.603 回答