Does Task.Wait(int) stop the task if the timeout elapses without the task finishing?

Viewed 46851

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 Answers

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.

Related