This recipe will describe how to wait on a thread without involving kernel-mode constructs. In addition, we introduce SpinWait
, a hybrid synchronization construct designed to wait in the 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 2015. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter2\Recipe9
.
To understand how to wait on a thread without involving kernel-mode constructs, perform the following steps:
Start Visual Studio 2015. Create a new C# console application project.
In the
Program.cs
file, add the followingusing
directives:using System; using System.Threading; using static System.Console; using static System.Threading.Thread;
Below the
Main
method, add the following code:static volatile bool _isCompleted = false; static void UserModeWait() { while (!_isCompleted) { Write("."); ...