Is this the proper use of a mutex?

You said multiple instances of one application, so we're talking about two program.exe's running, right? The lock statement won't lock across multiple programs, just within the program. If you want a true Mutex, look at the System.Threading.Mutex object.

Here is a usage example:

bool createdNew;
using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew))
{
    try
    {
        mtx.WaitOne();

        MessageBox.Show("Click OK to release the mutex.");
    }
    finally
    {
        mtx.ReleaseMutex();
    }
}

The createdNew variable will let you know whether or not it was created the first time. It only tells you if it has been created, though. If you want to acquire the lock, you need to call WaitOne and then call ReleaseMutex to release it. If you just want to see if you created a Mutex, just constructing it is fine.


TheSeeker is correct.

Jeff Richter's advice in Clr Via C# (p638-9) on locking is to create a private object specifically for the purpose of being locked.

private Object _lock = new Object();

// usage
lock( _lock )
{
    // thread-safe code here..
}

This works because _lock cannot be locked by anything outside the current class.

EDIT: this is applicable to threads executing within a single process. @David Mohundro's answer is correct for inter-process locking.

Tags:

C#

Mutex