How can I create a System Mutex in C#

c#, multithreading, mutex

Solution

There is a constructor overload for checking for an existing mutex.

http://msdn.microsoft.com/en-us/library/bwe34f1k(v=vs.90).aspx

So...

void doWorkWhileHoldingMutex()
{
    Console.WriteLine("   Sleeping...");
    System.Threading.Thread.Sleep(1000);
}

var requestInitialOwnership = true;
bool mutexWasCreated;
Mutex m = new Mutex(requestInitialOwnership, 
         "MyMutex", out mutexWasCreated);

if (requestInitialOwnership && mutexWasCreated)
{
    Console.WriteLine("We own the mutex");
}
else
{
    Console.WriteLine("Mutex was created, but is not owned. Waiting on it...");
    m.WaitOne();
    Console.WriteLine("Now own the mutex.");
}
doWorkWhileHoldingMutex();
Console.WriteLine("Finished working. Releasing mutex.");
m.ReleaseMutex();

If you fail to call `m.ReleaseMutex()` it will be called 'abandoned' when your thread exits. When another thread constructs the mutex, the exception `System.Threading.AbandonedMutexException` will be thrown telling him it was found in the abandoned state.

Problem

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.

Original source