在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
public Mutex ( bool initiallyOwned, string name, out bool createdNew ) 参数
static void Main(string[] args) { Thread th1 = new Thread(Thread1); Thread th2 = new Thread(Thread2); th1.Start(); th2.Start(); Console.ReadKey(); } public static void Thread1() { bool bCreatedNewMutex; Mutex m = new Mutex(true, "HAHA", out bCreatedNewMutex); //如果名为"HAHA"的互斥锁不存在,返回参数bCreatedNewMutex为true,否则为false if (bCreatedNewMutex) //如果名为“HAHA”的互斥锁不存在 { Console.WriteLine("th1装逼成功"); } else { Console.WriteLine("th1装逼失败"); } } public static void Thread2() { bool bCreatedNewMutex; Mutex m = new Mutex(true, "HAHA", out bCreatedNewMutex); if (bCreatedNewMutex) { Console.WriteLine("th2装逼成功"); } else { Console.WriteLine("th2装逼失败"); } } 二、使用了垃圾回收 static void Main(string[] args) { Thread th1 = new Thread(Thread1); Thread th2 = new Thread(Thread2); th1.Start(); th2.Start(); Console.ReadKey(); } public static void Thread1() { bool bCreatedNewMutex; Mutex m = new Mutex(true, "HAHA", out bCreatedNewMutex); if (bCreatedNewMutex) { Console.WriteLine("th1装逼成功"); } else { Console.WriteLine("th1装逼失败"); } } public static void Thread2() { Thread.Sleep(1000); //作用是等th1执行完毕,否则会报错:由于出现被放弃的 mutex,等待过程结束。 GC.Collect(); GC.WaitForPendingFinalizers(); bool bCreatedNewMutex; Mutex m = new Mutex(true, "HAHA", out bCreatedNewMutex); m.WaitOne(); if (bCreatedNewMutex) { Console.WriteLine("th2装逼成功"); } else { Console.WriteLine("th2装逼失败"); } m.ReleaseMutex(); }
|
请发表评论