I have the following code for sample console application, but the method specified in Task continuation using TaskContinuationOptions.OnlyOnFaulted
never gets called.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Sample
{
class Program
{
public static void Main(string[] args)
{
int index = 0;
var cts = new CancellationTokenSource();
Task.Factory.StartNew(() => NewTask(index), cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default)
.ContinueWith(HandleException, cts.Token, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default);
// Some code
// ...
Console.ReadLine();
}
private static async Task NewTask(int index)
{
Console.WriteLine(index);
await Wait();
}
private static async Task Wait()
{
await Task.Delay(500);
throw new Exception("Testing 123");
}
private static void HandleException(Task task)
{
if (task != null && task.Exception != null)
{
var exceptions = task.Exception.Flatten().InnerExceptions;
if (exceptions != null)
foreach (var exception in exceptions)
Console.WriteLine(exception.Message);
}
}
}
}
Here, when an exception is thrown from Wait()
method, instead of HandleException(...)
being called, either program crashes or debugger shows an unhandled exception dialog box.
EDITED: Return type of NewTask
method is Task
.