Когда я начал понимать через 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();
}
Я поставил блок try catch для Task.WaitAll (task1, task2). В идеале он должен достигать точки останова в выражении ex.handler внутри блока Catch. Как я понимаю, каким бы ни был результат, он должен попасть в блок catch.
То же самое происходит, если у меня есть task1.Result / task2.Result.
Мой вопрос таков: в режиме отладки почему точка останова не попадает в блок catch, когда я намеренно выбрасываю ее из задачи, поскольку я хочу исследовать операторы в блоке catch. Он просто ставит желтую отметку при произнесении «NullReferenceException, необработанного кодом пользователя».
Task task2 = new Task(() => {
throw new NullReferenceException();
});
Как мне попасть в точку останова в блоке catch ???
Спасибо за ответ:)