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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…