Task.WaitAll and canceled tasks
I have two ContinueWith for a task. The first handles the case when the task completed successfully, and the second handles the case when it fails. Then I wait until one of them is finished. Sample code below:
var task = Task.Factory.StartNew(() => { Console.WriteLine("Task is finished"); });
var success = task.ContinueWith(
t => Console.WriteLine("Success")
, TaskContinuationOptions.OnlyOnRanToCompletion
);
var failed = task.ContinueWith(
t => Console.WriteLine("Failed")
, TaskContinuationOptions.NotOnRanToCompletion
);
try
{
Task.WaitAll(success, failed);
}
catch (AggregateException ex)
{
Console.WriteLine(ex.InnerException.Message);
}
My question is, can I rewrite it to avoid throwing a TaskCanceledException?
+3
source to share
1 answer
If you want to have handlers for both success and failure, I don't see much reason to have them in separate calls ContinueWith()
. One call, which will always be, should suffice:
var continuation = task.ContinueWith(
t =>
{
if (t.IsFaulted)
Console.WriteLine("Failed");
else
Console.WriteLine("Success");
});
continuation.Wait();
Assuming it task
never gets reversed, this will behave in much the same way as the original code.
+2
source to share