Kill task


  • What is the recommended way to kill a Tasks.Task (not cancel).

    Scenario: WPF window. User decides a task takes to long to complete.

    According to my tests simply closing the window (or the app) seems to work.

    Tuesday, February 16, 2010 12:35 PM


All replies

  • Shutting down the application will work, however, this is somewhat harsh.

    Typically you want to avoid "killing" a task.  Cancellation is the appropriate way to handle this situation.  If you were to be able to "kill" a task (like calling Thread.Abort), all of the issues that arise with Thread.Abort would arise.  Killing a task without cancellation is always risky - it leaves the thread in an indeterminant state, since you have no control over what code happens to be executing at the time.  This would be particularly troublesome with Tasks, since Tasks are executed on ThreadPool threads.

    Cancellation is much cleaner, however, since a cancellation allows you, as the developer, to control when in the task the cancellation occurs, and prevent data from being left in a bad state.

    Reed Copsey, Jr. -
    Tuesday, February 16, 2010 5:02 PM
  • I agree on trying to cancel first.

    But if this takes to long the user will kill the process (it this works) or switch off the machine if the app does not shutdown fast.

    One can see how important this scenario is from the following post with more than 10000 contributions:
    Tuesday, February 16, 2010 6:35 PM
  • That won't be an issue, though -

    Since a Task runs on a ThreadPool thread, the thread on which the Task is executing is a background thread.  Background threads never prevent an application from shutting down.

    In this situation, just close your application - the thread will die naturally.  If the application is still running, however, just let the task continue (in the background) until it can be finished or canceled properly.

    Reed Copsey, Jr. -
    Tuesday, February 16, 2010 6:38 PM