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

Paul Mendoza picture Paul Mendoza · Oct 27, 2010 · Viewed 43.3k times · Source

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?

Answer

Nick Martyshchenko picture Nick Martyshchenko · Oct 27, 2010

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();