Are there any benefits for using a CancellationTokenSource over a volatile boolean field for signalling a Task to finish?
Of course yes. There are many. I'll list few.
CancellationTokensupports callbacks. You can be notified when the cancellation is requested.CancellationTokensupportsWaitHandlewhich you could wait for indefinitely or with a timeout.- You can schedule the cancelation of
CancellationTokenusingCancellationTokenSource.CancelAftermethod. - You can link your
CancellationTokento another, so that when one is cancelled another can be considered as cancelled. - By
Taskif you meanSystem.Threading.Tasks.Taska volatile boolean cannot transition the state of the Task to cancelled butCancellationTokencan.
来源:https://stackoverflow.com/questions/30024969/cancellationtokensource-vs-volatile-boolean