Udostępnij za pośrednictwem


Wait Synchronization Technology Sample

This sample demonstrates how to use the WaitHandle class for thread synchronization. The WaitHandle-derived type Mutex is used to enforce mutually exclusive access to a protected block of code.

For more information about using the samples, see the following topics:

To build the sample using the command prompt

  1. Open the Command Prompt window and navigate to one of the language-specific subdirectories for the sample.

  2. Type msbuild WaitSynchronizationCS.sln or msbuild WaitSynchronizationVB.sln, depending on your choice of programming language, at the command line.

To build the sample using Visual Studio

  1. Open Windows Explorer and navigate to one of the language-specific subdirectories for the sample.

  2. Double-click the icon for WaitSynchronizationCS.sln or WaitSynchronizationVB.sln, depending on your choice of programming language, to open the file in Visual Studio.

  3. On the Build menu, click Build Solution.

To run the sample

  1. Navigate to the directory that contains the new executable file.

  2. Type Mutex.exe from the command line.

    Note

    This sample builds a console application. You must launch it from a console window to view its output.

Remarks

This sample queues up five asynchronous method calls. Each method then waits to own the resource, writes to the console, sleeps, and then writes to the console a second time.

The following bullets briefly describe the technologies and classes used by this sample:

  • Thread Synchronization

    • Mutex Provides mutual exclusion for thread synchronization.

    • AutoResetEvent The sample's main thread waits on an AutoResetEvent until it is set. This indicates that the last of the asynchronous functions are finished doing their work.

    • WaitHandle The WaitHandle class is the base class from which both Mutex and AutoResetEvent classes (among others) are derived. This type implements methods to "wait" for the various derived types to go "signaled".

    • Interlocked The sample uses the static Decrement method to access a counter variable asynchronously to indicate when the AutoResetEvent should be set.

  • Threading

    • ThreadPool When writing managed code, it is suggested that, whenever possible, developers use the QueueUserWorkItem method to implement asynchronous method calls. This sample uses this approach to execute code that contends for a logical resource.
  • Delegates

For more information about threading and synchronization, see the comments in the source code and build.proj files.

See Also

Concepts

Threads and Threading

Reference

AutoResetEvent

Delegate

Interlocked

Mutex

System.Threading

ThreadPool

WaitCallback

WaitHandle

Other Resources

Threading Objects and Features