I'm working through the examples in the Exam Ref 70-483: Programming in C# book and have run into a problem with the following code from listing 1-44. In this example, the author is trying to demonstrate that a continuation task has access to unhandled exceptions thrown in the antecedent task, and can handle them if it is appropriate to do so.
static void Main(string[] args)
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
Task task = Task.Run(() =>
{
while (!token.IsCancellationRequested)
{
Console.Write("*");
Thread.Sleep(1000);
}
throw new OperationCanceledException();
}, token).ContinueWith((t) =>
{
t.Exception.Handle((e) => true);
Console.WriteLine("You have canceled the task.");
}, TaskContinuationOptions.OnlyOnCanceled);
Console.WriteLine("Press enter to stop the task.");
Console.ReadLine();
cancellationTokenSource.Cancel();
task.Wait();
Console.WriteLine("Press enter to end the application.");
Console.ReadLine();
}
Unfortunately, this line of code in the continuation
t.Exception.Handle((e) => true);
throws an exception because t.Exception
is null
.
Setting a breakpoint at that line, I can see that t.Status
is Canceled
, not Faulted
. Is this why the exception is not available? What is the correct way to handle the exception thrown in the antecedent task?
Use
task.ContinueWith(HandleError, TaskContinuationOptions.OnlyOnFaulted);
Cancelled tasks are not exceptional... And therefore will not include an exception. Faulted ones will.
Change the code for Listing 1-44 to:
Task task = Task.Run(() => {
while (true)
{
token.ThrowIfCancellationRequested();
Console.Write("*");
Thread.Sleep(1000); }
}, token).ContinueWith(t =>
{ Console.WriteLine("You have canceled the task"); }, TaskContinuationOptions.OnlyOnCanceled);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.