Suspending a Task using a CancellationToken in .NET C#
January 31, 2014 4 Comments
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 WaitOne method of the WaitHandle property of the CancellationToken object.
Construct the CancellationToken object as follows:
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationToken cancellationToken = cancellationTokenSource.Token;
The WaitOne() method without parameters suspends the Task execution until the Cancel() method of the CancellationToken object has been called. It has two overloads where you can specify some time: the amount of time to wait in milliseconds or some TimeSpan. The task suspension lasts until the sleep time is over OR the Cancel() method on the cancellation token has been called, whichever happens first. The WaitOne method also has a boolean return value where ‘true’ means that the Task has been cancelled and false means the the allotted sleep time was over.
You can use the cancellation token and the WaitOne method as follows:
Task task = Task.Factory.StartNew(() => { for (int i = 0; i < 1000000; i++) { bool cancelled = cancellationToken.WaitHandle.WaitOne(10000); Console.WriteLine("Value {0}. Cancelled? {1}", i, cancelled); if (cancelled) { throw new OperationCanceledException(cancellationToken); } } }, cancellationToken);
You can cancel the task as follows:
cancellationTokenSource.Cancel();
View the list of posts on the Task Parallel Library here.
But keep in mind: The CancellationTokenSouce is consumed. U can’t use it again. It’s state will always be IsCancellationRequested = true.
Sure, just like a Task cannot be started more than once.
Do you have a blog here on WordPress? You seem to know a lot about TPL.
//Andras
No, i have no blog but I’m thinking about it.
Quite a bit 😉 I am reading a lot of blogs and books.
I like your blog, so I’m trying to provide some helpful comments. 🙂
Nice blog article. How can I use Task.Factory.StartNew and also pass a TaskCreationOptions.LongRunning alongside the CancellationToken? There does not seem to be an overload for that.