标签:Thread 进程同步 C# private protected static new Mutex
参考MSDN官方:
Mutex 构造函数
贴入官方代码:
1 // This example shows how a Mutex is used to synchronize access 2 // to a protected resource. Unlike Monitor, Mutex can be used with 3 // WaitHandle.WaitAll and WaitAny, and can be passed across 4 // AppDomain boundaries. 5 6 using System; 7 using System.Threading; 8 9 class Test 10 { 11 // Create a new Mutex. The creating thread does not own the 12 // Mutex. 13 private static Mutex mut = new Mutex(); 14 private const int numIterations = 1; 15 private const int numThreads = 3; 16 17 static void Main() 18 { 19 // Create the threads that will use the protected resource. 20 for(int i = 0; i < numThreads; i++) 21 { 22 Thread myThread = new Thread(new ThreadStart(MyThreadProc)); 23 myThread.Name = String.Format("Thread{0}", i + 1); 24 myThread.Start(); 25 } 26 27 // The main thread exits, but the application continues to 28 // run until all foreground threads have exited. 29 } 30 31 private static void MyThreadProc() 32 { 33 for(int i = 0; i < numIterations; i++) 34 { 35 UseResource(); 36 } 37 } 38 39 // This method represents a resource that must be synchronized 40 // so that only one thread at a time can enter. 41 private static void UseResource() 42 { 43 // Wait until it is safe to enter. 44 mut.WaitOne(); 45 46 Console.WriteLine("{0} has entered the protected area", 47 Thread.CurrentThread.Name); 48 49 // Place code to access non-reentrant resources here. 50 51 // Simulate some work. 52 Thread.Sleep(500); 53 54 Console.WriteLine("{0} is leaving the protected area\r\n", 55 Thread.CurrentThread.Name); 56 57 // Release the Mutex. 58 mut.ReleaseMutex(); 59 } 60 }
标签:Thread,进程同步,C#,private,protected,static,new,Mutex 来源: https://www.cnblogs.com/chenxiaolinembed/p/15355737.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。