Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
260 views
Welcome To Ask or Share your Answers For Others

1 Answer

  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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...