1using System; 2using System.Threading; 3using System.Threading.Tasks; 4namespace InterProcessSynchronization 5{ 6 class InterProcessSync 7 { 8 static void Main(string[] args) 9 { 10 string MutexName = "InterProcessSyncName"; 11 Mutex SyncNamed; //声明一个已命名的互斥对象 12 try 13 { 14 SyncNamed = Mutex.OpenExisting(MutexName); //如果此命名互斥对象已存在则请求打开 15 } 16 catch (WaitHandleCannotBeOpenedException) 17 { 18 SyncNamed = new Mutex(false, MutexName); //如果初次运行没有已命名的互斥对象则创建一个 19 } 20 Task MulTesk = new Task 21 ( 22 () => //多任务并行计算中的匿名方法,用委托也可以 23 { 24 for (; ; ) //为了效果明显而设计 25 { 26 Console.WriteLine("当前进程等待获取互斥访问权......"); 27 SyncNamed.WaitOne(); 28 Console.WriteLine("获取互斥访问权,访问资源完毕,按回车释放互斥资料访问权."); 29 Console.ReadLine(); 30 SyncNamed.ReleaseMutex(); 31 Console.WriteLine("已释放互斥访问权。"); 32 } 33 } 34 ); 35 MulTesk.Start(); 36 MulTesk.Wait(); 37 } 38 } 39}
以上程序编译后,请运行两个实例即两个进程。就可以明显的看出进程间的同步的实现。