Search code examples
c#async-awaittask-parallel-librarycancellationtokensource

Run a task when another task was canceled in C#


I have the following requirements:

  • launch Task1,2 in parallel.
  • Task 5 will launch when 1 of 2 Tasks 1,2 is completed.
  • Task 4 will launch only when Task 5 is cancelled.

Below is my code but it is not working. Is it possible that I want to launch a task when another task is cancelled?

Task.WhenAny(runTask1(), runTask2()).ContinueWith((t0) => 
{
    runTask5();
    
    if (runTask5().Status == TaskStatus.Canceled)
    {
        runTask4();
    }
});

Solution

  • _ = await Task.WhenAny(runTask1(), runTask2());
    try
    {
       await runTask5();
    }
    catch(OperationCancelledException ex)
    {
       await runTask4();
    }
    

    You can await Tasks inside catch and finally blocks since C# 6.