Thread.SpinWait Example
This page was last reviewed on Sep 11, 2023.
Dot Net Perls
SpinWait. An idle loop uses 100% CPU. It runs for a specified number of iterations in a C# program. With Thread.SpinWait we specify this iteration count.
Some notes. The CPU will max out for the required amount of time for this to complete. Meanwhile with Thread.Sleep, no CPU usage will occur.
Example. This program uses Thread.SpinWait for one million iterations. It also uses Stopwatch to time how long Thread.SpinWait takes to complete.
Result An argument of 1000000 required about 3 milliseconds to complete on the computer used for testing.
Note Because SpinWait is computationally intensive, it will complete earlier or later depending on your computer's clock speed.
using System; using System.Diagnostics; using System.Threading; Stopwatch stopwatch = Stopwatch.StartNew(); // CPU is at maximum during this call. // ... (Try making it much larger to test.) Thread.SpinWait(1000000); Console.WriteLine(stopwatch.Elapsed.TotalMilliseconds);
Discussion. I tried to determine how to adjust the number of threads optimally for a multiple-core machine. SpinWait was helpful in this task.
Info When I used Thread.Sleep, the experiment did not involve the CPU and so did not yield correct results.
But When I used Thread.SpinLock, the results were correct. SpinLock is necessary to simulate actual CPU usage.
Summary. We looked at Thread.SpinWait found in the System.Threading namespace. If you want to waste electricity and make your computer do a lot of computations, this method is perfect.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 11, 2023 (edit).
© 2007-2024 Sam Allen.