views:

209

answers:

3

How can I create a system/multiprocess Mutex to co-ordinate multiple processes using the same unmanaged resource.

Background: I've written a procedure that uses a File printer, which can only be used by one process at a time. If I wanted to use it on multiple programs running on the computer, I'd need a way to synchronize this across the system.

+1  A: 

without seeing your code it is tough to give specific advise but there is a mutex class in c#

MSDN

Pharabus
+3  A: 

You can use the System.Threading.Mutex class, which has an OpenExisting method to open a named system mutex.

280Z28
Thanks, didn't realize that method was what I wanted.
C. Ross
+4  A: 

You can use the System.Threading.Mutex class, which has an OpenExisting method to open a named system mutex.

It's a minor point, but that doesn't answer the question:

How can I create a system/multiprocess Mutex

To create a system-wide mutex, call the System.Threading.Mutex constructor that takes a string as an argument. This is also known as a 'named' mutex. To see if it exists, I can't seem to find a more graceful method than try catch:

System.Threading.Mutex _mutey = null;
try
{
    _mutey = System.Threading.Mutex.OpenExisting("mutex_name");
    //we got Mutey and can try to obtain a lock by waitone
    _mutey.WaitOne();
}
catch 
{
    //the specified mutex doesn't exist, we should create it
    _mutey = new System.Threading.Mutex("mutex_name"); //these names need to match.
}

Now, to be a good programmer, you need to, when you end the program, release this mutex

_mutey.ReleaseMutex();

or, you can leave it in which case it will be called 'abandoned' when your process exits, and will allow another process to create it.

Limited Atonement