Search code examples
c#.netwinformstask-parallel-librarycancellation

Task cancellation from inside the task body


I read about the Cancellation methods but based on my understanding they all provide control over tasks from outside the task, but if i want to cancel a task from the inside.

For example in this pseudo code:

Task tasks = new Task(() =>
{ 
     bool exists = CheckFromDB();
      if (!exists)
         break;
}

Can i cancel a task from the inside? The only idea i got is to trigger an exception inside the task and handle it from outside but surly that is not the way to do.


Solution

  • If you want to truly Cancel the task (e.g. after it's completed the Status property would be set to Canceled), you can do it this way:

    var cts = new CancellationTokenSource();
    var token = cts.Token;
    
    Task innerCancel = new Task(
        () =>
        {
            if (!CheckFromDB())
            {
                cts.Cancel();
            }
            token.ThrowIfCancellationRequested();
        },
        token);
    

    When you use return task won't be actually canceled, but rather code after the return statement won't be executed, and the task itself will have its state as RanToCompletion.


    On a side note it's advised to use Task.Factory.StartNew for .NET 4 and Task.Run for .NET 4.5 instead of constructor to create tasks.