This recipe will describe how to wait on a thread without involving kernel-mode constructs. In addition, we introduce SpinWait
, a hybrid synchronization construct, which is designed to wait in user mode for some time, and then switch to the kernel mode to save CPU time.
To step through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe could be found at BookSamples\Chapter2\Recipe9
.
To understand waiting on a thread without involving kernel-mode constructs, perform the following steps:
Start Visual Studio 2012. Create a new C# Console Application project.
In the
Program.cs
file, add the followingusing
directives:using System; using System.Threading;
Below the
Main
method, add the following code:static volatile bool _isCompleted = false; static void UserModeWait() { while (!_isCompleted) { Console.Write("."); } Console.WriteLine(); Console.WriteLine("Waiting is...