6

I want to use CancellationTokenSource stop the Task. My tests as follow:

Test 1 : Using Cancel() stopped the task sucessfully.

Test 2 : Using CancelAfter() did not stop the task, Why?

The task action is:

    static Action testFun = () => {
        Thread.Sleep(4000); // or other a long time operation
        Console.WriteLine("Action is end");
    };

The test1 code:

        CancellationTokenSource source = new CancellationTokenSource(); 
        CancellationToken token = source.Token;
        //Register the cancel action
        token.Register(() =>
        {
            Console.WriteLine("Task is canceled");
        });
        Task task = new Task(testFun, token); 
        task.Start();
        source.Cancel();     
        Console.ReadLine();

Output is:

Task is canceled

Test2 Code:

        CancellationTokenSource source = new CancellationTokenSource(); 
        CancellationToken token = source.Token;
        //Register the cancel action
        token.Register(() =>
        {
            Console.WriteLine("Task is canceled");
        });
        Task task = new Task(testFun, token); 
        task.Start();
        source.CancelAfter(100); // the time 100ms < the task 4000ms
        Console.ReadLine();

Output is:

Task is canceled
Action is end

My question is why task is still running when CancelAfter() is invoked on CancellationTokenSource

How do I revise the test2 ? Thank you.

9
  • possible duplicate of stackoverflow.com/questions/17717625/… Feb 25, 2018 at 7:52
  • The answer is : Sleep method is ignoring the CancellationToken. But I use some other long time Funtion() replace the Sleep(), the problem is still in. I want know how the CancelAfter() do not stop the Task.
    – longt
    Feb 25, 2018 at 8:05
  • Sleep method is nothing but calling Thread.Sleep() Feb 25, 2018 at 8:08
  • 2
    The problem is that cancelationToken is misleading. Once task is started you cannot cancel it unless you explicitly check cancelationToken. You can only prevent task to even start and that is exactly what happend with Cancel
    – Johnny
    Feb 25, 2018 at 8:21
  • 2
    Exactly, as expected, task won't be stopped once it is started, look at my answer what is philosophy behind camcelation token...
    – Johnny
    Feb 25, 2018 at 8:56

3 Answers 3

8

The CancelationToken is kind of a misleading. The problem is that if Task is already started it cannot be stopped unless you explicitly check CancelationToken, for example CancellationToken.ThrowIfCancellationRequested. The purpose of the CancelationToken is to prevent the Task to start while it is still scheduled.

That is difference in your example, with Cancel you cancel the task while it is still scheduled but with CancelAfter task is already started and there is no way to stop it anymore.

First, the CancellationToken. If you cancel the token before the continuation is scheduled, then the continuation delegate never actually runs - it’s cancelled. However, note that the token does not cancel the continuation once it has started. In other words, the CancellationToken cancels the scheduling of the continuation, not the continuation itself. For this reason, I think the CancellationToken parameter is misleading, and I never use it myself.

https://blog.stephencleary.com/2015/01/a-tour-of-task-part-7-continuations.html

Part explaining the continuation of the Task but it is the same also with the Task itself, continuation will schedule new task anyway.

CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;

//If cancelAfter > taskWaiting - task will be finished
//If canceAfter < taskWaiting - task will be canceled
//If cancelAfter == taskWaiting - unexpected :)
int cancelAfter = 100;
int taskWaiting = 200;          

//If token is canceled before run of the task it won't start at all
//source.Cancel();

//Register the cancel action
token.Register(() =>
{
    Console.WriteLine("Task is canceled");
});

Task.Run(() =>
{
    Console.WriteLine("Action is started");
    Thread.Sleep(taskWaiting);

    if (token.IsCancellationRequested)
        return;             

    Console.WriteLine("Action is finished");
}, token);          

source.CancelAfter(cancelAfter);
4
  • Thanks .You mean the task is running, it can't be stopped unless check CancelationToken? But in some longtime action, the check is after the action. Is there nice way to check the CancelationToken?
    – longt
    Feb 25, 2018 at 9:35
  • Yes, exactly Task won't stop once it is started. The way it either check IsCancellationRequested or ThrowIfCancellationRequested(). Be carefull that exception can be packed within AggregatedException depends how you are using TPL api (await will buble original exception, task.wait will pack it...).
    – Johnny
    Feb 25, 2018 at 10:11
  • When run source.Cancel() as above, the task can't be started indeed. But call source.Cancel() in the task running code span, the task can be start and then to stop. Their two methods stop the task: 1-use "thread.Abort()" , the thread is the running task's thread; 2-call source.Cancel() . Those steps must run int the Task running code. Example:‘Task.Run(() => { Console.WriteLine("Task start"); source.Cancel(); token.ThrowIfCancellationRequested(); }, token);’
    – longt
    Feb 26, 2018 at 16:07
  • If you set source.Cancel before run the task then task scheduler will throw TaskCanceledException but you are not handling it. You can try to await the task and wrap it with the try-catch block... The same is happening with the Task.Delay(4000) what Evk suggest... btw Thread.Abort is harmful should be avoided
    – Johnny
    Feb 26, 2018 at 16:19
1

Cancel() succeeds in cancelling that task, because task had no chance to even start. When task is scheduled and it about to run - there is a check if its not already cancelled. You can verify it by modifying testFun like this:

static Action testFun = () => {
    Console.WriteLine("start");
    Thread.Sleep(4000); // or other a long time operation
    Console.WriteLine("Action is end");
};

And observe that when you use Cancel - there is no "start" output to console, so task has not been started.

When you introduce a delay with CancelAfter, or by just doing:

Task task = new Task(testFun, token);
task.Start();
Thread.Sleep(10); // < small delay
source.Cancel();

Task has a chance to start, and after it has been started - cancelling token has no effect, because nothing in the body of testFunc checks if token has been cancelled. It's not possible for task to be magically cancelled in the middle of execution without cooperation from that task code.

Cooperation can look for example like this (though using Task.Delay in this way is not usually recommended):

static Action<CancellationToken> testFun = (CancellationToken ct) => {
    Console.WriteLine("start");
    Task.Delay(4000, ct).Wait();
    Console.WriteLine("Action is end");
};

Then when you start task - you pass cancellation token there:

Task task = new Task(() => testFun(token), token);

And now there is cooperation - Task.Delay will notice that token is cancelled and will cancel Task.Delay operation, which in turn will cancel your task (by throwing OperationCanceledException).

Same can be done with async\await:

static async Task TestFun(CancellationToken ct) {
    Console.WriteLine("start");
    await Task.Delay(4000, ct);
    Console.WriteLine("Action is end");
}

Task task = TestFun(token);
// no need for task.Start() here - task is already started
source.CancelAfter(100);
Console.ReadLine();
5
  • Follow the question: the Task.Delay is defin the task running after timespan, so it can be work. My purpose is run a task like http request.
    – longt
    Feb 25, 2018 at 9:06
  • I replace the Task.Delay 'await Task.Run(() => { WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); Console.WriteLine("Response is end"); }, ct); // await Task.Delay(0,ct);' When the url is timeout (the cancel action run), but the task is not stopped. After a while, the "Response is end“ output .
    – longt
    Feb 25, 2018 at 9:17
  • @longt well web request is different. You can either use WebRequest.Timeout (then GetResponse will throw exception if no response is received after timeout), or use technique described here: stackoverflow.com/q/19211972/5311735
    – Evk
    Feb 25, 2018 at 9:43
  • I know the WebRequest.Timeout, I just puzzled in Task. The problem has been resolved. When the task is run, create a new task checking the CancellationToken , when the cancel event occured, use the Thread.Abort() to stop the running task.
    – longt
    Feb 25, 2018 at 9:51
  • 1
    "use the Thread.Abort() to stop the running task" is never a solution.
    – Evk
    Feb 25, 2018 at 9:55
-1

The core problem is the Task won't stop once it is started.

It must be check the IsCancellationRequested.

There is one way to solve this problem:

when task is running , use Thread.CurrentThread to get the thread, and create a new Task to listen the running task's CancellationToken. In the listening function:listening the status of cancel, call thread.Abort() if cancel event is ture. Use Abort() is a unsafe way,but it can stop the task.

The code as follow:

    static void Main(string[] args)
    {
        // If the task running used 3000ms, stop.
        int timeOut = 3000;
        CancellationTokenSource source = new CancellationTokenSource();
        source.CancelAfter(timeOut);
        CancellationToken token = source.Token;
        token.Register(() =>
        {
            Console.WriteLine("Task Is TimeOut!!!!! Stop");
        });
        //start the task:
        Task.Run(() =>
        {
            Console.WriteLine("Task start");
            Thread thread = Thread.CurrentThread;
            //create a new task listening the token;
            Task.Factory.StartNew(() =>
            {
                Console.WriteLine("Listening start");
                while (!token.IsCancellationRequested)
                {
                    Console.WriteLine("Listening...");
                    Thread.Sleep(800);
                }
                Console.WriteLine("Listening End");
                thread.Abort();
            }, token);

            Stopwatch time = Stopwatch.StartNew();
            #region A long time operation:;
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("run...");
                Thread.Sleep(100);
            }
            #endregion
            time.Stop();
            Console.WriteLine("Task end. cost:{0}", time.ElapsedMilliseconds);
            source.Cancel();
            Console.WriteLine("Task End");
            token.ThrowIfCancellationRequested();
        }, token);
        Console.ReadLine();
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.