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:

1.
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.
2.
At the beginning of the code, place ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.