Coordinating Threads with the Mutex Class

The .NET Compact Framework includes the Mutex class, which is a useful entity for coordinating threads. The Mutex class's name is derived from the term mutual exclusion. The class creates a region of code that can be executed by only one thread at a time.

A Mutex works by tracking which thread “holds” it. Only one thread may hold a Mutex at a time. If another thread tries to acquire it, then it blocks until the first thread releases its hold.

To use a Mutex to force only one thread to execute code at a time, follow these steps:

Create an instance of the Mutex class. Pass false into the Mutex constructor so that the code that created the Mutex does not hold it.
At the beginning of the code, place ...

Get Microsoft® .NET Compact Framework Kick Start now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.