Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force a task cancellation?

Assume, there is a task containing the following actions approximately:

Task someTask = new Task(() => {

  while(!IsCancellationRequested) {

    Do_something_over_a_long_period_of_time();
    token.ThrowIfCancellationRequested();

    Do_something_over_a_long_period_of_time();
    token.ThrowIfCancellationRequested();

    Do_something_over_a_long_period_of_time();
    token.ThrowIfCancellationRequested();
  }
});
someTask.Start();

And there are pretty impatient users. They long to terminate my application immediately. They don't want to wait while long action is running.

I used to use the Thread class and was able to abort all my threads immediately with invoking the Abort() command.

How do I abort my tasks immediately?

Thank you.

like image 644
Jean Louis Avatar asked Mar 14 '11 13:03

Jean Louis


People also ask

What is force cancel?

Force cancel a task Force canceling a task stops the task and its sub-tasks immediately and does not use the Task Cancel Grace Period.

How do you cancel task in Windows?

In the task list, select one or more tasks. Right-click your selection and click Cancel Task.

What is task Cancelled exception?

TaskCanceledException(String, Exception, CancellationToken) Initializes a new instance of the TaskCanceledException class with a specified error message, a reference to the inner exception that is the cause of this exception, and the CancellationToken that triggered the cancellation.


2 Answers

You can't force a task to abort in an uncooperative manner. Aborting a thread in an uncontrolled way is unsafe, and thus deliberately unsupported.

You should make your Do_something_over_a_long_period_of_time calls cancellable instead (i.e. pass them the token, and make them check regularly too).

EDIT: As noted in another answer, you can kill the application just by making sure all the foreground threads have terminated. But you need to be aware that your tasks won't necessarily have had a chance to terminate cleanly. If they're doing things like writing files, you may well want to wait until the cancellation has been noticed, to avoid corrupting persisted state.

like image 66
Jon Skeet Avatar answered Oct 22 '22 09:10

Jon Skeet


They long to terminate my application immediately. They dont want to wait while long action is running.

By default, Tasks run on the ThreadPool as background tasks. You can safely exit the application without bothering about background threads.

So as long as you want to quit your process there is no problem.

Note that Thread.Abort() was quick but not safe. Not even for a quitting application, but then it would seldom cause a real problem.

like image 32
Henk Holterman Avatar answered Oct 22 '22 08:10

Henk Holterman