Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.WaitAll and cancelled tasks

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?

like image 328
Teddy Bo Avatar asked Dec 13 '25 03:12

Teddy Bo


1 Answers

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.

like image 82
svick Avatar answered Dec 15 '25 17:12

svick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!