1

在以下使用 EventWaitHandle 确保单实例应用程序的示例中,设置 EventWaitHandleSecurity 的正确方法是什么?

    /// <summary>
    /// The method either:
    /// 1) acquires mutex and starts listing if anyone tries to get the same mutex,
    /// or
    /// 2) notifies the instance that actually owns the mutex
    /// </summary>
    /// <param name="isSystemWide">
    /// true if mutex is system wide (can belong to any user of the system),
    /// false if there could be one mutex per active user
    /// </param>
    /// <param name="instanceName">The name of the mutex</param>
    /// <param name="callback">Callback to be raised after the mutex is acquired
    /// on every time another instance tries (and fails) to acquire the mutex</param>
    /// <returns>
    /// true if mutex is acquired (and event is subsribed),
    /// false otherwise (and the mutex owner is notified)
    /// </returns>
    public static bool TryListenOrNotify(bool isSystemWide, string instanceName, Action callback)
    {
        var name = (isSystemWide ? "Global" : "Local") + "\\" + instanceName;

        var securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, (SecurityIdentifier)null);
        var rule = new EventWaitHandleAccessRule(securityIdentifier, EventWaitHandleRights.FullControl, AccessControlType.Allow);
        var waitHandleSecurity = new EventWaitHandleSecurity();
        waitHandleSecurity.AddAccessRule(rule);

        bool createdNew;
        var eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, name, out createdNew, waitHandleSecurity);
        if(createdNew)
        {
            // mutex not acquired
            var thread = new Thread(() =>
            {
                using(eventWaitHandle)
                {
                    // listening for notifications
                    while(eventWaitHandle.WaitOne())
                    {
                        callback();
                    }
                }
            });
            thread.IsBackground = true;
            thread.Start();
            return true;
        }
        else
        {
            // mutex is not acquired
            using(eventWaitHandle)
            {
                // notifying the mutex owner
                eventWaitHandle.Set();
            }
            return false;
        }
    }

特别是,我不喜欢盲目地授予所有人所有访问权限。但我无法弄清楚默认安全设置是什么,在这种情况下设置的最低权限是什么?

谢谢你。

4

0 回答 0