Suspending a Task using Thread.Sleep in .NET C#
February 4, 2014 Leave a comment
You may want to put a Task to sleep for some time. You might want to check the state of an object before continuing. The Task continues after the sleep time.
One way to solve this is using the classic Thread.Sleep method since the Task library uses .NET threading support in the background.
First construct your cancellation token:
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationToken cancellationToken = cancellationTokenSource.Token;
Use this token in the constructor of the task:
Task task = Task.Factory.StartNew(() => { for (int i = 0; i < 100000; i++) { Thread.Sleep(10000); Console.WriteLine(i); cancellationToken.ThrowIfCancellationRequested(); } }, cancellationToken);
Note the Sleep method where we suspend the Task for 10 seconds.
You can use the cancellation token to interrupt the task:
cancellationTokenSource.Cancel();
In the previous post we discussed how to suspend a task using the WaitOne method of the cancellation token. The main difference between WaitOne and Sleep is that Sleep will block even if the task is cancelled whereas WaitOne will exit if the cancellation come before the sleep time is over.
View the list of posts on the Task Parallel Library here.