I have console application and code as below,
My problem is before ContinueWith task finish, the console application ends, it does not waits the continueWith to fini
Jorge's solution is not working when an exception is thrown :
var task = new Task(() =>
{
Console.WriteLine("My task...");
throw new Exception();
});
task.Start();
var taskNotOnFaulted = task.ContinueWith(t =>
{
Thread.Sleep(1000);
Console.WriteLine("NotOnFaulted");
}, TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
var taskOnlyOnFaulted = task.ContinueWith(t =>
{
Thread.Sleep(1000);
Console.Write("OnlyOnFaulted");
}, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
Task.WaitAny(taskNotOnFaulted, taskOnlyOnFaulted);
Console.WriteLine("Finished");
The output is :
My task...
Finished
OnlyOnFaulted
This is because the taskNotOnFaulted get a Cancelled status when the exception is thrown, whereas it keeps a WaitingForActivation status when no exception is thrown.
So you have to replace :
Task.WaitAny(taskNotOnFaulted, taskOnlyOnFaulted);
by
if (task.IsFaulted)
taskOnlyOnFaulted.Wait();
else
taskNotOnFaulted.Wait();