0

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?

usr
  • 168,620
  • 35
  • 240
  • 369

1 Answers1

3

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();
        }
usr
  • 168,620
  • 35
  • 240
  • 369
Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
  • 1
    That was the problem. I added test code to your answer. In 9min I will accept your answer (system limit). – usr Feb 24 '12 at 15:30