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
CancellationToken
allows the token to handle all necessary synchronization, so you don't have to think about it.Task
faults due to the token used in its creation being marked as cancelled it sets the state of the Task
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With