当我开始通过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语句中命中断点。据我所知,无论结果如何,它都应该击中捕获区。
如果我有task1.Result / task2.Result,则会发生同样的情况。
我的问题是:在调试模式下,当我故意将其从任务中抛出时,为什么不在catch块中命中断点,因为我想检查catch块下的语句。它只是将黄色标记放在“用户代码未处理的NullReferenceException”上。
Task task2 = new Task(() => {
throw new NullReferenceException();
});
如何在catch区块中找到断点???
感谢您的回复:)
答案 0 :(得分:0)
正如Arne Claassen在其注释中所解释的那样,调试器在抛出原始异常时暂停执行,因为线程不处理异常。如果继续执行( F5 或播放按钮),程序应继续到您继续处理异常的位置。