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.
CancellationToken
supports callbacks. You can be notified when the cancellation is requested.CancellationToken
supportsWaitHandle
which you could wait for indefinitely or with a timeout.- You can schedule the cancelation of
CancellationToken
usingCancellationTokenSource.CancelAfter
method. - You can link your
CancellationToken
to another, so that when one is cancelled another can be considered as cancelled. - By
Task
if you meanSystem.Threading.Tasks.Task
a volatile boolean cannot transition the state of the Task to cancelled butCancellationToken
can.
来源:https://stackoverflow.com/questions/30024969/cancellationtokensource-vs-volatile-boolean