【问题标题】:How to hit the breakpoint at catch block when working with TPL使用 TPL 时如何在 catch 块处命中断点
【发布时间】:2012-09-20 16:04:00
【问题描述】:


当我开始通过 TPL 理解时。我陷入了这段代码中。我有 2 个任务。 Task1 抛出 ArgumentOutOfRangeException,Task2 抛出 NullReferenceException。

考虑以下代码:

static void Main(string[] args) {

            // create the cancellation token source and the token
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;

            // create a task that waits on the cancellation token
            Task task1 = new Task(() => {
                // wait forever or until the token is cancelled
                token.WaitHandle.WaitOne(-1);
                // throw an exception to acknowledge the cancellation
                throw new OperationCanceledException(token);
            }, token);

            // create a task that throws an exceptiono
            Task task2 = new Task(() => {
                throw new NullReferenceException();
            });

            // start the tasks
            task1.Start(); task2.Start();

            // cancel the token
            tokenSource.Cancel();

            // wait on the tasks and catch any exceptions
            try {
                Task.WaitAll(task1, task2);
            } catch (AggregateException ex) {
                // iterate through the inner exceptions using 
                // the handle method
                ex.Handle((inner) => {
                    if (inner is OperationCanceledException) {
                        // ...handle task cancellation...
                        return true;
                    } else {
                        // this is an exception we don't know how
                        // to handle, so return false
                        return false;
                    }
                });
            }

            // wait for input before exiting
            Console.WriteLine("Main method complete. Press enter to finish.");
            Console.ReadLine();
        }

我已经为 Task.WaitAll(task1, task2) 放置了 try catch 块。理想情况下,它应该在 Catch 块内的 ex.handler 语句中命中断点。据我了解,无论结果如何,它都应该命中 catch 块。

如果我有 task1.Result/task2.Result,也会发生同样的情况。

我的问题是:在调试模式下,当我故意将断点从任务中抛出时,为什么没有在 catch 块处命中断点,因为我想检查 catch 块下的语句。它只是在“用户代码未处理的 NullReferenceException”处加上黄色标记。

Task task2 = new Task(() => {
                throw new NullReferenceException();
            });

如何在 catch 块处打断点???

感谢回复:)

【问题讨论】:

  • 当我运行这段代码时,我确实得到了用户未处理的中断(因为它没有被那个线程处理),但是当我继续它时,它会在 catch 内遇到断点,并且被捕获的 AggregateException 不会包含两个抛出的异常。

标签: parallel-processing breakpoints task-parallel-library


【解决方案1】:

正如Arne Claassen 在他们的评论中解释的那样,调试器会在引发原始异常的点暂停执行,因为线程不处理异常。如果您继续执行(F5播放按钮),程序应继续执行到您在继续中处理异常的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 2010-12-15
    • 2011-07-09
    • 1970-01-01
    • 2019-11-12
    相关资源
    最近更新 更多