Home >Backend Development >C++ >How to Implement Robust Global Mutex Patterns in C#?
The Mutex class in C#provides a mechanism to control access to multiple threads or processes sharing resources. The global mutual mutual body has a systematic scope, and has proposed unique challenges in ensuring safe and reliable use. This article discusses a comprehensive model of creating and effective use of global mutual expeckets, and solves the key aspects of regional setting independence, correct mutual dismissal release, and processing abnormal conditions.
Mode implementation
The following code example shows the reliable mode of using the global mutual body:
Key features
<code class="language-csharp">using System.Runtime.InteropServices; //GuidAttribute using System.Reflection; //Assembly using System.Threading; //Mutex using System.Security.AccessControl; //MutexAccessRule using System.Security.Principal; //SecurityIdentifier // ... // 主应用程序逻辑 static void Main(string[] args) { // 获取应用程序的唯一GUID string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly() .GetCustomAttributes(typeof(GuidAttribute), false) .GetValue(0)).Value.ToString(); // 创建全局唯一的互斥体ID string mutexId = string.Format( "Global\{{{0}}}", appGuid ); // 为多用户使用建立安全设置 var allowEveryoneRule = new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid , null) , MutexRights.FullControl , AccessControlType.Allow ); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); // 使用指定的ID和安全设置初始化互斥体 using (var mutex = new Mutex(false, mutexId, out bool createdNew, securitySettings)) { // 尝试获取互斥体句柄,设置超时 var hasMutexHandle = false; try { hasMutexHandle = mutex.WaitOne(5000, false); } catch (AbandonedMutexException) { // 记录日志并获取被放弃的互斥体 hasMutexHandle = true; } // 在互斥体范围内执行关键操作 if (hasMutexHandle) { // ... mutex.ReleaseMutex(); } } }</code>
Independence of regional settings: The mutualized ID uses the GUID generation of the application to ensure that it is unique in different areas.
The above is the detailed content of How to Implement Robust Global Mutex Patterns in C#?. For more information, please follow other related articles on the PHP Chinese website!