Home > Backend Development > C++ > How to Implement Robust Global Mutex Patterns in C#?

How to Implement Robust Global Mutex Patterns in C#?

Patricia Arquette
Release: 2025-01-30 22:12:13
Original
390 people have browsed it

How to Implement Robust Global Mutex Patterns in C#?

C#The reliable realization of the global mutual body mode

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

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();
        }
    }
}
Copy after login

Independence of regional settings: The mutualized ID uses the GUID generation of the application to ensure that it is unique in different areas.

  • 保证互斥体释放: using块在超出范围时自动释放互斥体,消除了悬空互斥体的风险。
  • Out time processing:
  • Specify the optional overtime when obtaining the mutually exclusive body to prevent unlimited waiting. The abandoned mutually exclusive treatment:
  • Elegant to obtain the abandoned mutual body to ensure that the program execution will not be blocked indefinitely.
  • Multi -user security: Mutual exclusion to grant explicit access permissions to all users, allowing collaboration and resource sharing.
  • Conclusion
  • 此模式为在C#中使用全局互斥体提供了坚实的基础,确保安全可靠的执行。 By following these criteria, developers can effectively manage sharing resources and prevent potential issues related to the use of mutual alternatives.

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template