I have two ContinueWith for a task. The first one handles the case when the task is finished successfully and the second one for the case when it fails. Then I wait till one of them is finished. The sample code is 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, is it possible to rewrite it to avoid TaskCanceledException raising?
When you want to have handlers for both success and failure, I don't see much reason to have them in separate ContinueWith() calls. One call, that will happen always should be enough:
var continuation = task.ContinueWith(
t =>
{
if (t.IsFaulted)
Console.WriteLine("Failed");
else
Console.WriteLine("Success");
});
continuation.Wait();
Assuming task will never be canceled, this will behave pretty much the same as your original code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With