34
votes

I have a task and I expect it to take under a second to run but if it takes longer than a few seconds I want to cancel the task.

For example:

Task t = new Task(() =>
        {
            while (true)
            {
                Thread.Sleep(500);
            }
        });
t.Start();
t.Wait(3000);

Notice that after 3000 milliseconds the wait expires. Was the task canceled when the timeout expired or is the task still running?

5
Why not use cancellation api?Nick Martyshchenko
What is the cancellation API?Paul Mendoza
check my answer I put some links about itNick Martyshchenko

5 Answers

16
votes

If you want to cancel a Task, you should pass in a CancellationToken when you create the task. That will allow you to cancel the Task from the outside. You could tie cancellation to a timer if you want.

To create a Task with a Cancellation token see this example:

var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;

var t = Task.Factory.StartNew(() => {
    // do some work
    if (token.IsCancellationRequested) {
        // Clean up as needed here ....
    }
    token.ThrowIfCancellationRequested();
}, token);

To cancel the Task call Cancel() on the tokenSource.

53
votes

Task.Wait() waits up to specified period for task completion and returns whether the task completed in the specified amount of time (or earlier) or not. The task itself is not modified and does not rely on waiting.

Read nice series: Parallelism in .NET, Parallelism in .NET – Part 10, Cancellation in PLINQ and the Parallel class by Reed Copsey

And: .NET 4 Cancellation Framework / Parallel Programming: Task Cancellation

Check following code:

var cts = new CancellationTokenSource();

var newTask = Task.Factory.StartNew(state =>
                           {
                              var token = (CancellationToken)state;
                              while (!token.IsCancellationRequested)
                              {
                              }
                              token.ThrowIfCancellationRequested();
                           }, cts.Token, cts.Token);


if (!newTask.Wait(3000, cts.Token)) cts.Cancel();
7
votes

The task is still running until you explicitly tell it to stop or your loop finishes (which will never happen).

You can check the return value of Wait to see this:

(from http://msdn.microsoft.com/en-us/library/dd235606.aspx) Return Value

Type: System.Boolean true if the Task completed execution within the allotted time; otherwise, false.

6
votes

Was the task canceled when the timeout expired or is the task still running?

No and Yes.

The timeout passed to Task.Wait is for the Wait, not the task.

-1
votes

If your task calls any synchronous method that does any kind of I/O or other unspecified action that takes time, then there is no general way to "cancel" it.

Depending on how you try to "cancel" it, one of the following may happen:

  • The operation actually gets canceled and the resource it works on is in a stable state (You were lucky!)
  • The operation actually gets canceled and the resource it works on is in an inconsistent state (potentially causing all sorts of problems later)
  • The operation continues and potentially interferes with whatever your other code is doing (potentially causing all sorts of problems later)
  • The operation fails or causes your process to crash.
  • You don't know what happens, because it is undocumented

There are valid scenarios where you can and probably should cancel a task using one of the generic methods described in the other answers. But if you are here because you want to interrupt a specific synchronous method, better see the documentation of that method to find out if there is a way to interrupt it, if it has a "timeout" parameter, or if there is an interruptible variation of it.