时间:2022-10-05 11:21:49 | 栏目:.NET代码 | 点击:次
Mutex的突出特点是可以跨应用程序域边界对资源进行独占访问,即可以用于同步不同进程中的线程,这种功能当然这是以牺牲更多的系统资源为代价的。
主要常用的两个方法:
案例一:
class Program { private static Mutex mutex = new Mutex(); static void Main(string[] args) { Thread[] thread = new Thread[3]; for (int i = 0; i < 3; i++) { thread[i] = new Thread(ThreadMethod1);//方法引用 thread[i].Name = "Thread-" + (i+1).ToString(); } for (int i = 0; i < 3; i++) { thread[i].Start(); } Console.ReadKey(); } public static void ThreadMethod1(object val) { mutex.WaitOne(); //获取锁 for (int i = 1; i <=5; i++) { Console.WriteLine("{0}循環了{1}次", Thread.CurrentThread.Name, i); } mutex.ReleaseMutex(); //释放锁 } }
运行结果:
案例二:
class Program { private static Mutex mutex = new Mutex(); private static int sum = 0; static void Main(string[] args) { Task<int> task = new Task<int>(ThreadFunction); task.Start(); Console.WriteLine($"{DateTime.Now} task started!"); Thread.Sleep(2000);//Main主線程 Console.WriteLine($"{DateTime.Now} Get siginal in Main!"); mutex.WaitOne(); Console.WriteLine($"{DateTime.Now} Get siginal in main!"); Console.WriteLine($"{DateTime.Now} Result is {task.Result}"); Console.ReadKey(); } private static int ThreadFunction() { Console.WriteLine($"{DateTime.Now} Get siginal in ThreadFunction!"); mutex.WaitOne(); //获取锁 for (int i = 0; i <= 10; i++) { sum += i; Thread.Sleep(1000); } Console.WriteLine($"{DateTime.Now} Release mutex in ThreadFunction!"); mutex.ReleaseMutex(); //释放锁 return sum; } }
运行结果:
为避免发送多线程发生死锁,Mutex的WaitOne()和ReleaseMutex()需成对配合使用。