Suspending a Task using a CancellationToken in .NET C#

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.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

4 Responses to Suspending a Task using a CancellationToken in .NET C#

  1. Stefan Ossendorf says:

    But keep in mind: The CancellationTokenSouce is consumed. U can’t use it again. It’s state will always be IsCancellationRequested = true.

  2. Stefan Ossendorf says:

    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. 🙂

  3. Joerg says:

    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: