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.
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);3.0908
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 11, 2023 (edit).