Search code examples
taskcancellationtokensource

CancellationTokenSource vs manually ending Task


Say I create a task

bool aBoolean = true;

Task.Factory.StartNew(() =>
    while(aBooloean)    {
       ...
    }
}

Is it better to exit the task by having a global boolean to exit the Task?

Or ist it better to use CancellationTokenSource?

When is it appropriate to use a CancellationTokenSource to end a Task?

Does it just throw an exception when you use CancellationTokenSource and leave things in a inconsistent state?

Thanks


Solution

  • Having a "global" boolean runs the risk of being optimized or cached into CPU cache and you may not see a change in value. CancellationTokenSource is the recommended method for cancelling a Task. The Task uses the Token to test if cancellation is requested and simply returns from the Task's Action delegate. No need to throw an exception if you don't want to.