Search code examples
.netmultithreadingsynchronizationmutexsingle-instance

Mutual Exclusion not Working with the .NET Mutex Class


How can I achieve mutual exclusion using two named mutexes? The following code should work but it doesn't:

    [TestMethod]
    public void xdfgndygfn()
    {
        using (var mutex1 = new Mutex(false, "1234"))
        using (var mutex2 = new Mutex(false, "1234"))
        {
            mutex1.WaitOne();
            mutex2.WaitOne(); //this should block, but it doesn't
        }
    }

Using Process Explorer I verified that there are two mutex handles referring to the same name. This should work... What am I missing?


Solution

  • From MSDN:

    The thread that owns a mutex can request the same mutex in repeated calls to WaitOne without blocking its execution.

    Here is a test to verify this (the test will not complete):

            using (var mutex1 = new Mutex(false, "1234"))
            using (var mutex2 = new Mutex(false, "1234"))
            {
                var t1 = new Thread(() =>
                    {
                        mutex1.WaitOne();
                        Thread.Sleep(1000000);
                    });
                var t2 = new Thread(() =>
                    {
                        mutex2.WaitOne();
                        Thread.Sleep(1000000);
                    });
    
                t1.Start();
                t2.Start();
    
                t1.Join();
                t2.Join();
            }