Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 845
Paul Mendoza Avatar asked Oct 27 '10 17:10

Paul Mendoza


People also ask

How does task Wait work?

Wait is a synchronization method that causes the calling thread to wait until the current task has completed. If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread.

How to cancel task Wait in C#?

You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource. CancelAfter method if you don't want to wait for the operation to finish.

How to use Wait() in C#?

To wait for a single task to complete, you can call its Task. Wait method. A call to the Wait method blocks the calling thread until the single class instance has completed execution. The parameterless Wait() method is used to wait unconditionally until a task completes.

How to Wait a thread in C#?

In C#, Thread class provides the Join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t. Join() causes the current thread to pause its execution until thread it joins completes its execution.


2 Answers

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.

like image 39
Brian Rasmussen Avatar answered Sep 30 '22 07:09

Brian Rasmussen


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(); 
like image 186
Nick Martyshchenko Avatar answered Sep 30 '22 05:09

Nick Martyshchenko