Использование EventWaitHandle, чтобы обеспечить приложение одного экземпляра с уведомлениями

Как правильно настроить EventWaitHandleSecurity в следующем примере, который использует EventWaitHandle для обеспечения единственного экземпляра приложения?

    /// <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;
        }
    }

В частности, я не люблю вслепую предоставлять всем доступ каждому. Но я не могу понять, каковы настройки безопасности по умолчанию и какие минимальные привилегии установлены в этом случае?

Спасибо.

0 ответов

Другие вопросы по тегам