One of the benefits of using multiple threads in an application is that each thread executes synchronously. For Windows applications, this allows time-consuming tasks to be performed in the background while the application window and controls remain responsive. For server applications, multithreading provides the ability to handle each incoming request with a different thread. Otherwise, each new request would not get serviced until the previous request had been fully satisfied.However, the asynchronous nature of threads means that access to resources such as file handles, network connections, and memory must be coordinated. Otherwise, two or more threads could access the same resource at the same time, each unaware of the other's actions. The result is unpredictable data corruption.
For all other data types and non thread-safe resources, multithreading can only be safely performed using the following constructs:-
- A lock is specific to the AppDomain, lock is a compiler keyword, not an actual class or object. It's a wrapper around the functionality of the
r
class and is designed to make the Monitor easier to work with for the common case. - The Monitor (and the lock keyword) are restricted to the AppDomain primarily because a reference to a memory address (in the form of an instantiated object) is required to manage the "lock" and maintain the identity of the Monitor.
- A Mutex is global (within the OS or within a kernel namespace). Mutex is specific to the Operating System allowing you to perform cross-process locking or inter-process thread synchronization. Mutexes are of two types: local mutex, which are unnamed and named system mutex.
- The Mutex (Named) will stop any process on the same machine accessing it as well, whereas lock will only stop other threads in the same process.
- It seems good practice to hold the simple lock for a short period of time - but then the much heavier interprocess named Mutex.
- The Mutex, on the other hand, is a .Net wrapper around an operating system construct, and can be used for system-wide synchronization, using string data (instead of a pointer to data) as its identifier. Two Mutexes that reference two strings in two completely different memory addresses, but having the same data, will actually utilize the same operating-system Mutex.
- Although a Mutex can be used for intra-process thread synchronization, using Monitor is generally preferred, because monitors were designed specifically for the .NET Framework and therefore make better use of resources. In contrast, the Mutex class is a wrapper to a Win32 construct. While it is more powerful than a monitor, a mutex requires interop transitions that are more computationally expensive than those required by the Monitor class.
- Mutex is a cross process and there is a classic example of not running more than one instance of an application.