2
當我開始瞭解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)。理想情況下,它應該在Catch塊內的ex.handler語句中觸發斷點。據我瞭解,無論結果如何,它都應該觸及catch catch。如果我有task1.Result/task2.Result
同一案件中正在發生的事情。
我的問題是:在調試模式爲什麼沒有斷點被在catch塊擊中時,我特意從任務扔它,因爲我要檢查下catch塊的語句。它只是說黃色標記「NullReferenceException未被用戶代碼處理」。
Task task2 = new Task(() => {
throw new NullReferenceException();
});
我該如何在抓塊上打斷點???
感謝回答:)
當我運行這段代碼,我得到了用戶未處理突破(因爲它是由線程未處理的),但是當我繼續它然後打Catch中的斷點和抓AggregateException確實包含兩個拋出的異常。 –