Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between CancellationTokenSource and exit flag for Task loop exit

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

like image 212
Teamol Avatar asked Jan 14 '15 19:01

Teamol


1 Answers

  1. Using a CancellationToken allows the token to handle all necessary synchronization, so you don't have to think about it.
  2. When a 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.
  3. 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.
  4. It adds enhanced semantic meaning to the code.
like image 179
Servy Avatar answered Sep 17 '22 20:09

Servy