Monitor Synchronization Technology Sample
This sample demonstrates how to use the Monitor class for thread synchronization. The Monitor type's static functions are used to enforce mutually exclusive access to a protected block of code.
Review comments in the source code and build.proj files for more information on thread synchronization and the Monitor class.
For more information about using the samples, see the following topics:
To build the sample using the command prompt
Open a Command Prompt window and navigate to one of the language-specific subdirectories for the sample.
Type msbuild MonitorSynchronizationCS.sln or msbuild MonitorSynchronizationVB.sln, depending on your choice of programming language, at the command line.
To build the sample using Visual Studio
Open Windows Explorer and navigate to one of the language-specific subdirectories for the sample.
Double-click the icon for MonitorSynchronizationCS.sln or MonitorSynchronizationVB.sln, depending on your choice of programming language, to open the file in Visual Studio.
On the Build menu, click Build Solution.
To run the sample
Navigate to the directory that contains the new executable, using the command prompt.
Type Monitor.exe from the command line.
This sample builds a console application. You must launch it using the command prompt in order to view its output. When running the sample, notice that the "Start Writing" and "Stop Writing" output for each writer occurs successively without overlap from threads with different IDs. This is because the threads hold exclusive access to the resource.
The following bullets briefly describe the classes and technologies used by this sample.
Monitor Provides static functions for entering and exiting a protected block of code. You cannot instantiate an instance of the Monitor type. Instead, you pass to its static methods a reference to any object-derived type that you wish to use as a single node of synchronization.
Both Visual Basic and C# implement special keywords to take advantage of the Monitor type's static methods. C# uses the lock keyword, and Visual Basic uses the SyncLock keyword.