With the introduction of Win32 came preemptive multitasking. Preemptive multitasking means that a thread may be interrupted at any time to allow another thread to process. This happens without regard to the state of the thread. This also means that if one thread is trying to write to a variable and another thread is trying to read that same variable, the outcome can be indeterminate. Imagine raising an apple to eat it and at the same time you begin to take a bite, someone else shoves his head in there and takes a bite first. Besides potentially getting an unexpected taste of human hair, the result is that you don't get what you wanted or expected. If you don't employ some sort of synchronization scheme in your multithreaded applications, this is essentially the same problem that can occur. In this section, you will see and use the different synchronization types and the ways that they are implemented in .NET.

Understanding the Different Types of Synchronization

As with everything, there are many ways to accomplish the same task. Each way takes a different approach, and with each approach comes some advantages and disadvantages. The same holds true with the different synchronization schemes. Table 9.3 lists the four basic types of synchronization and the corresponding .NET class that uses each scheme.

Table 9.3. Win32 Basic Synchronization Types

Synchronization Type


Corresponding .NET Class(es)


A mutex synchronization prevents more then one thread from accessing a shared resource at a time.


Critical Section

A critical section synchronization does the same thing as a mutex, but with one exception: It does not work across processes.

lock, Monitor, Interlocked, ReaderWriterLock


A semaphore synchronization limits the number of threads that can access the same shared resource.



An event synchronization can signal other threads to perform specific actions.

AutoResetEvent, ManualResetEvent, WaitHandle

    Visual C#. NET 2003 Unleashed
    Visual C#. NET 2003 Unleashed
    ISBN: 672326760
    EAN: N/A
    Year: 2003
    Pages: 316 © 2008-2017.
    If you may any questions please contact us: