Domanda

Come posso ottenere un'esclusione reciproca usando due mutasi denominati?Il seguente codice dovrebbe funzionare ma non è:

    [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
        }
    }
.

Utilizzo del processo Explorer Ho verificato che ci sono due maniglie del mutex che si riferiscono allo stesso nome.Questo dovrebbe funziona ... cosa mi manca?

È stato utile?

Soluzione

Da msdn :

.

Il filo che possiede un mutex può richiedere lo stesso mutex nelle chiamate ripetute di attesa senza bloccare la sua esecuzione.

Ecco un test per verificare questo (il test non sarà completato):

        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();
        }
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top