Suspending a Task using SpinWait 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 Thread.SpinWait 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++)
}, cancellationToken);

You can use the cancellation token to interrupt the task:


We looked at Thread.Sleep and the WaitOne method in the previous posts on TPL. With those two techniques the thread that’s currently performing the task gives up its turn while sleeping. This gives a chance to other threads to do something. With spin waiting it’s different as the thread does not give up its turn.

The integer argument in SpinWait indicates an iteration. It is the number of times that a tight CPU loop will be performed. The exact amount of sleep time will depend on the speed of the CPU so it’s not some well defined period of time. Therefore spin waiting doesn’t stop using the CPU.

Bear in mind these limitations and use SpinWait with care – if ever.

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.

Leave a Reply

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

You are commenting using your 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


Once Upon a Camayoc

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

%d bloggers like this: