Synchronization between applications using the mutex name

I want to sync between 2 appdomains, but can't make it work.

I have it:

static void Main(string[] args) { using (Mutex m = new Mutex(true, "Global\\m")) { AppDomain ad = AppDomain.CreateDomain("ad"); var dllName = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath; ad.CreateInstanceFrom(dllName, typeof(Consumer).FullName); Thread.Sleep(4000); m.ReleaseMutex(); } Console.ReadLine(); } 

and

 public class Consumer { public Consumer() { //var createdNew = false; //Mutex m = new Mutex(false, "Global\\m", out createdNew); Mutex m = Mutex.OpenExisting("Global\\m"); m.WaitOne(); Console.WriteLine("Done"); } } 

I expect Done to print in 4 seconds, but it will print immediately.

I tried creating a mutex at the consumer using the constructor and using OpenExisting - it does not matter. Do not think that naming the mutex "Global" matters in this case, but tried it.

Something must be missed, and I canโ€™t understand what .. help?

0
source share
1 answer

A mutex belongs to a thread, and they are recursive, that is, they can be reintroduced into a single thread. Using a mutex to simultaneously exclude other threads from the same resource. All you did was create a mutex belonging to the calling thread, and then wait on it. Since the thread already owns the mutex, WaitOne returns immediately.

To see the delay, you have to call OpenExisting and WaitOne in another thread. For demonstration purposes, you can try the following:

 public Consumer() { Task.Run(() => { Mutex m = Mutex.OpenExisting("Global\\m"); m.WaitOne(); Console.WriteLine("Done"); }); } 
+1
source

All Articles