Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

c# - 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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
  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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...