问题
I was wondering if there is any difference between ending loop task with CancellationTokenSource and exit flag
CancellationTokenSource:
CancellationTokenSource cancellationTokenSource;
Task loopTask;
void StartLoop()
{
cancellationTokenSource = new CancellationTokenSource();
loopTask = Task.Factory.StartNew(Loop, TaskCreationOptions.LongRunning);
}
void Loop()
{
while (true)
{
if (cancellationTokenSource.IsCancellationRequested)
break;
Thread.Yield();
}
}
void StopLoop()
{
cancellationTokenSource.Cancel();
loopTask = null;
cancellationTokenSource = null;
}
Exit flag:
volatile bool exitLoop;
Task loopTask;
void StartLoop()
{
exitLoop = false;
loopTask = Task.Factory.StartNew(Loop, TaskCreationOptions.LongRunning);
}
void Loop()
{
while (true)
{
if (exitLoop)
break;
Thread.Yield();
}
}
void StopLoop()
{
exitLoop = true;
loopTask = null;
}
To me it does not make any sance to use CancellationTokenSource, btw is there any reason why cancellation token can be add as a parameter to Task factory?
Thank you very much for any kind of answer.
Best ragards teamol
回答1:
- Using a
CancellationToken
allows the token to handle all necessary synchronization, so you don't have to think about it. - When a
Task
faults due to the token used in its creation being marked as cancelled it sets the state of theTask
to cancelled, rather than faulted. If you use a boolean (and don't throw) the task would actually be marked as completed successfully, even though it was actually cancelled. - Unlike a boolean it's a reference type, so the reference to the CTS can be passed around and cancelled (or inspected) from other locations. This is key in that these locations don't need to be coupled together the way that they would if you used a boolean field; neither the code deciding when the operation is cancelled, nor any of the code reacting to the cancellation, need to know about each other. This allows for greater modularization, abstraction, higher levels of functionality not specific to individual circumstances, etc.
- It adds enhanced semantic meaning to the code.
来源:https://stackoverflow.com/questions/27950848/difference-between-cancellationtokensource-and-exit-flag-for-task-loop-exit