TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Thread.SpinWait Example

This C# example program shows the SpinWait method from System.Threading. SpinWait causes actual CPU usage.

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. The CPU will max out for the required amount of time for this to complete.

Example. This program uses Thread.SpinWait for one million iterations. It also uses Stopwatch to time how long Thread.SpinWait takes to complete. An argument of 1000000 required about 3 milliseconds to complete on the computer used for testing.

Stopwatch

Note: Because SpinWait actually is computationally intensive, it will complete earlier or later depending on your computer's clock speed.

C# program that uses Thread.SpinWait

using System;
using System.Diagnostics;
using System.Threading;

class Program
{
    static void Main()
    {
	Stopwatch stopwatch = Stopwatch.StartNew();
	// CPU is maxed out during this call.
	// ... (Try making it much larger to test.)
	Thread.SpinWait(1000000);
	Console.WriteLine(stopwatch.Elapsed.TotalMilliseconds);
    }
}

Output

3.0908

Discussion. There is an interesting use for Thread.SpinWait that I have found during testing. Several years ago I did a ThreadPool experiment. I tried to determine how to adjust the number of threads optimally for a multiple-core machine.

And: 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.

ThreadPool.SetMinThreads

Summary. We looked at the Thread.SpinWait method found in the System.Threading namespace in the .NET Framework. If you want to waste electricity and make your computer do a lot of wasteful computations, this method is perfect.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf