18.7. Synchronizing Multiple Processes with the Mutex
Problem
You have two processes or AppDomains that are running code with actions that you need to coordinate.
Solution
Use a named Mutex
as a common signaling mechanism to do the coordination. A named Mutex
can be accessed from both pieces of code even when running in different processes or AppDomains.
One situation in which this can be useful is when you are using shared memory to communicate between processes. The SharedMemoryManager
class presented in this recipe will show the named Mutex
in action by setting up a section of shared memory that can be used to pass serializable objects between processes. The "server" process creates a SharedMemoryManager
instance, which sets up the shared memory and then creates the Mutex
as the initial owner. The "client" process then also creates a SharedMemoryManager
instance that finds the shared memory and hooks up to it. Once this connection is established, the "client" process then sets up to receive the serialized objects and waits until one is sent by waiting on the Mutex
the "server" process created. The "server" process then takes a serializable object, serializes it into the shared memory, and releases the Mutex
. It then waits on it again so that when the "client" is done receiving the object, it can release the Mutex
and give control back to the "server." The "client" process that was waiting on the Mutex
then deserializes the object from the shared memory and releases the Mutex
.
In the ...
Get C# 3.0 Cookbook, 3rd Edition 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.