EventWaitHandle.OpenExisting 메서드

정의

이미 있는 경우 지정한 명명된 동기화 이벤트를 엽니다.Opens a specified named synchronization event, if it already exists.

오버로드

OpenExisting(String)

이미 있는 경우 지정한 명명된 동기화 이벤트를 엽니다.Opens the specified named synchronization event, if it already exists.

OpenExisting(String, EventWaitHandleRights)

이미 있는 경우 지정한 명명된 동기화 이벤트를 원하는 보안 액세스로 엽니다.Opens the specified named synchronization event, if it already exists, with the desired security access.

OpenExisting(String)

이미 있는 경우 지정한 명명된 동기화 이벤트를 엽니다.Opens the specified named synchronization event, if it already exists.

public:
 static System::Threading::EventWaitHandle ^ OpenExisting(System::String ^ name);
[System.Security.SecurityCritical]
public static System.Threading.EventWaitHandle OpenExisting (string name);
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public static System.Threading.EventWaitHandle OpenExisting (string name);
public static System.Threading.EventWaitHandle OpenExisting (string name);
[<System.Security.SecurityCritical>]
static member OpenExisting : string -> System.Threading.EventWaitHandle
[<System.Runtime.Versioning.SupportedOSPlatform("windows")>]
static member OpenExisting : string -> System.Threading.EventWaitHandle
static member OpenExisting : string -> System.Threading.EventWaitHandle
Public Shared Function OpenExisting (name As String) As EventWaitHandle

매개 변수

name
String

열고 다른 프로세스와 공유할 동기화 개체의 이름입니다.The name of the synchronization object to be opened and shared with other processes. 이름은 대/소문자를 구분합니다.The name is case-sensitive.

반환

EventWaitHandle

명명된 시스템 이벤트를 나타내는 개체입니다.An object that represents the named system event.

특성

예외

이름이 name인 동기화 개체를 열 수 없습니다.A synchronization object with the provided name cannot be opened. 존재하지 않거나 다른 형식의 동기화 개체에 동일한 이름이 사용되었을 수 있습니다.It may not exist, or a synchronization object of a different type might have the same name. 잘못된 이름 때문에 이 예외가 throw되기도 합니다.In some cases, this exception may be thrown for invalid names.

name이 빈 문자열인 경우name is an empty string.

-또는--or-

.NET Framework에만 해당: name이 MAX_PATH(260자)보다 깁니다..NET Framework only: name is longer than MAX_PATH (260 characters).

name이(가) null인 경우.name is null.

name이 잘못되었습니다.name is invalid. 이유는 다양하며, 대표적인 이유는 운영 체제가 적용하는 일부 제한(예: 알 수 없는 접두사나 잘못된 문자)입니다.This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. 이름과 일반 접두사인 "Global" 및 "Local"은 대/소문자를 구분합니다.Note that the name and common prefixes "Global" and "Local" are case-sensitive.

-또는--or-

다른 오류가 발생했습니다.There was some other error. HResult 속성에서 자세한 정보를 확인할 수 있습니다.The HResult property may provide more information.

Windows에만 해당: name이 알 수 없는 네임스페이스를 지정했습니다.Windows only: name specified an unknown namespace. 자세한 내용은 개체 이름을 참조하세요.See Object Names for more information.

name이 너무 깁니다.The name is too long. 길이 제한은 운영 체제나 구성에 따라 달라집니다.Length restrictions may depend on the operating system or configuration.

명명된 이벤트가 있지만 사용자에게 이 이벤트를 사용하는 데 필요한 보안 액세스 권한이 없는 경우The named event exists, but the user does not have the security access required to use it.

예제

다음 코드 예제에서는 액세스 제어 보안을 사용 하는 명명 된 시스템 이벤트의 크로스 프로세스 동작을 보여 줍니다.The following code example demonstrates the cross-process behavior of a named system event with access control security. 이 예제에서는 메서드 오버 로드를 사용 하 여 OpenExisting(String) 명명 된 이벤트의 존재 여부를 테스트 합니다.The example uses the OpenExisting(String) method overload to test for the existence of a named event.

이벤트가 존재 하지 않는 경우 현재 사용자에 게 이벤트를 사용할 수 있는 권한을 거부 하 고 이벤트에 대 한 권한을 읽고 변경할 수 있는 권한을 부여 하는 초기 소유권 및 액세스 제어 보안을 사용 하 여 생성 됩니다.If the event does not exist, it is created with initial ownership and access control security that denies the current user the right to use the event, but grants the right to read and change permissions on the event.

두 명령 창에서 컴파일된 예제를 실행 하는 경우 두 번째 복사본은에 대 한 호출에서 액세스 위반 예외를 throw 합니다 OpenExisting(String) .If you run the compiled example from two command windows, the second copy will throw an access violation exception on the call to OpenExisting(String). 예외가 catch 되 고 예제에서는 메서드 오버 로드를 사용 하 여 OpenExisting(String, EventWaitHandleRights) 사용 권한을 읽고 변경 하는 데 필요한 권한을 사용 하 여 이벤트를 기다립니다.The exception is caught, and the example uses the OpenExisting(String, EventWaitHandleRights) method overload to wait on the event with the rights needed to read and change the permissions.

사용 권한이 변경 된 후에는 이벤트를 대기 하 고 신호를 보내는 데 필요한 권한을 사용 하 여 이벤트를 엽니다.After the permissions are changed, the event is opened with the rights required to wait on it and signal it. 세 번째 명령 창에서 컴파일된 예제를 실행 하는 경우이 예제는 새 사용 권한을 사용 하 여 실행 됩니다.If you run the compiled example from a third command window, the example runs using the new permissions.

using namespace System;
using namespace System::Threading;
using namespace System::Security::AccessControl;
using namespace System::Security::Permissions;

public ref class Example
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand,Flags=SecurityPermissionFlag::UnmanagedCode)]
   static void Main()
   {
      String^ ewhName = L"EventWaitHandleExample5";

      EventWaitHandle^ ewh = nullptr;
      bool doesNotExist = false;
      bool unauthorized = false;
      
      // The value of this variable is set by the event
      // constructor. It is true if the named system event was
      // created, and false if the named event already existed.
      //
      bool wasCreated;
      
      // Attempt to open the named event.
      try
      {
         // Open the event with (EventWaitHandleRights.Synchronize
         // | EventWaitHandleRights.Modify), to wait on and
         // signal the named event.
         //
         ewh = EventWaitHandle::OpenExisting( ewhName );
      }
      catch ( WaitHandleCannotBeOpenedException^ ) 
      {
         Console::WriteLine( L"Named event does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
         unauthorized = true;
      }

      // There are three cases: (1) The event does not exist.
      // (2) The event exists, but the current user doesn't
      // have access. (3) The event exists and the user has
      // access.
      //
      if ( doesNotExist )
      {
         // The event does not exist, so create it.

         // Create an access control list (ACL) that denies the
         // current user the right to wait on or signal the
         // event, but allows the right to read and change
         // security information for the event.
         //
         String^ user = String::Concat( Environment::UserDomainName, L"\\",
            Environment::UserName );
         EventWaitHandleSecurity^ ewhSec = gcnew EventWaitHandleSecurity;
         //following constructor fails
         EventWaitHandleAccessRule^ rule = gcnew EventWaitHandleAccessRule(
            user,
            static_cast<EventWaitHandleRights>(
               EventWaitHandleRights::Synchronize | 
               EventWaitHandleRights::Modify),
            AccessControlType::Deny );
         ewhSec->AddAccessRule( rule );

         rule = gcnew EventWaitHandleAccessRule( user,
            static_cast<EventWaitHandleRights>(
               EventWaitHandleRights::ReadPermissions | 
               EventWaitHandleRights::ChangePermissions),
            AccessControlType::Allow );
         ewhSec->AddAccessRule( rule );
         
         // Create an EventWaitHandle object that represents
         // the system event named by the constant 'ewhName',
         // initially signaled, with automatic reset, and with
         // the specified security access. The Boolean value that
         // indicates creation of the underlying system object
         // is placed in wasCreated.
         //
         ewh = gcnew EventWaitHandle( true,
            EventResetMode::AutoReset,
            ewhName,
            wasCreated,
            ewhSec );
         
         // If the named system event was created, it can be
         // used by the current instance of this program, even
         // though the current user is denied access. The current
         // program owns the event. Otherwise, exit the program.
         //
         if ( wasCreated )
         {
            Console::WriteLine( L"Created the named event." );
         }
         else
         {
            Console::WriteLine( L"Unable to create the event." );
            return;
         }
      }
      else if ( unauthorized )
      {
         // Open the event to read and change the access control
         // security. The access control security defined above
         // allows the current user to do this.
         //
         try
         {
            ewh = EventWaitHandle::OpenExisting( ewhName, 
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::ReadPermissions |
                  EventWaitHandleRights::ChangePermissions) );
            
            // Get the current ACL. This requires
            // EventWaitHandleRights.ReadPermissions.
            EventWaitHandleSecurity^ ewhSec = ewh->GetAccessControl();
            String^ user = String::Concat( Environment::UserDomainName, L"\\",
               Environment::UserName );
            
            // First, the rule that denied the current user
            // the right to enter and release the event must
            // be removed.
            EventWaitHandleAccessRule^ rule = gcnew EventWaitHandleAccessRule(
               user,
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::Synchronize |
                  EventWaitHandleRights::Modify),
               AccessControlType::Deny );
            ewhSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew EventWaitHandleAccessRule( user,
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::Synchronize |
                  EventWaitHandleRights::Modify),
               AccessControlType::Allow );
            ewhSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // EventWaitHandleRights.ChangePermissions.
            ewh->SetAccessControl( ewhSec );
            Console::WriteLine( L"Updated event security." );
            
            // Open the event with (EventWaitHandleRights.Synchronize
            // | EventWaitHandleRights.Modify), the rights required
            // to wait on and signal the event.
            //
            ewh = EventWaitHandle::OpenExisting( ewhName );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine( L"Unable to change permissions: {0}",
               ex->Message );
            return;
         }

      }
      
      // Wait on the event, and hold it until the program
      // exits.
      //
      try
      {
         Console::WriteLine( L"Wait on the event." );
         ewh->WaitOne();
         Console::WriteLine( L"Event was signaled." );
         Console::WriteLine( L"Press the Enter key to signal the event and exit." );
         Console::ReadLine();
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
      }
      finally
      {
         ewh->Set();
      }
   }
};

int main()
{
   Example::Main();
}
using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string ewhName = "EventWaitHandleExample5";

        EventWaitHandle ewh = null;
        bool doesNotExist = false;
        bool unauthorized = false;

        // The value of this variable is set by the event
        // constructor. It is true if the named system event was
        // created, and false if the named event already existed.
        //
        bool wasCreated;

        // Attempt to open the named event.
        try
        {
            // Open the event with (EventWaitHandleRights.Synchronize
            // | EventWaitHandleRights.Modify), to wait on and 
            // signal the named event.
            //
            ewh = EventWaitHandle.OpenExisting(ewhName);
        }
        catch (WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Named event does not exist.");
            doesNotExist = true;
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // There are three cases: (1) The event does not exist.
        // (2) The event exists, but the current user doesn't 
        // have access. (3) The event exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The event does not exist, so create it.

            // Create an access control list (ACL) that denies the
            // current user the right to wait on or signal the 
            // event, but allows the right to read and change
            // security information for the event.
            //
            string user = Environment.UserDomainName + "\\"
                + Environment.UserName;
            EventWaitHandleSecurity ewhSec = 
                new EventWaitHandleSecurity();

            EventWaitHandleAccessRule rule = 
                new EventWaitHandleAccessRule(user, 
                    EventWaitHandleRights.Synchronize | 
                    EventWaitHandleRights.Modify, 
                    AccessControlType.Deny);
            ewhSec.AddAccessRule(rule);

            rule = new EventWaitHandleAccessRule(user, 
                EventWaitHandleRights.ReadPermissions | 
                EventWaitHandleRights.ChangePermissions, 
                AccessControlType.Allow);
            ewhSec.AddAccessRule(rule);

            // Create an EventWaitHandle object that represents
            // the system event named by the constant 'ewhName', 
            // initially signaled, with automatic reset, and with
            // the specified security access. The Boolean value that 
            // indicates creation of the underlying system object
            // is placed in wasCreated.
            //
            ewh = new EventWaitHandle(true, 
                EventResetMode.AutoReset, 
                ewhName, 
                out wasCreated, 
                ewhSec);

            // If the named system event was created, it can be
            // used by the current instance of this program, even 
            // though the current user is denied access. The current
            // program owns the event. Otherwise, exit the program.
            // 
            if (wasCreated)
            {
                Console.WriteLine("Created the named event.");
            }
            else
            {
                Console.WriteLine("Unable to create the event.");
                return;
            }
        }
        else if (unauthorized)
        {
            // Open the event to read and change the access control
            // security. The access control security defined above
            // allows the current user to do this.
            //
            try
            {
                ewh = EventWaitHandle.OpenExisting(ewhName, 
                    EventWaitHandleRights.ReadPermissions | 
                    EventWaitHandleRights.ChangePermissions);

                // Get the current ACL. This requires 
                // EventWaitHandleRights.ReadPermissions.
                EventWaitHandleSecurity ewhSec = ewh.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\"
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the event must
                // be removed.
                EventWaitHandleAccessRule rule = 
                    new EventWaitHandleAccessRule(user, 
                        EventWaitHandleRights.Synchronize | 
                        EventWaitHandleRights.Modify, 
                        AccessControlType.Deny);
                ewhSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new EventWaitHandleAccessRule(user, 
                    EventWaitHandleRights.Synchronize | 
                    EventWaitHandleRights.Modify, 
                    AccessControlType.Allow);
                ewhSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // EventWaitHandleRights.ChangePermissions.
                ewh.SetAccessControl(ewhSec);

                Console.WriteLine("Updated event security.");

                // Open the event with (EventWaitHandleRights.Synchronize 
                // | EventWaitHandleRights.Modify), the rights required
                // to wait on and signal the event.
                //
                ewh = EventWaitHandle.OpenExisting(ewhName);
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}",
                    ex.Message);
                return;
            }
        }

        // Wait on the event, and hold it until the program
        // exits.
        //
        try
        {
            Console.WriteLine("Wait on the event.");
            ewh.WaitOne();
            Console.WriteLine("Event was signaled.");
            Console.WriteLine("Press the Enter key to signal the event and exit.");
            Console.ReadLine();
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
        }
        finally
        {
            ewh.Set();
        }
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const ewhName As String = "EventWaitHandleExample5"

        Dim ewh As EventWaitHandle = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

        ' The value of this variable is set by the event
        ' constructor. It is True if the named system event was
        ' created, and False if the named event already existed.
        '
        Dim wasCreated As Boolean

        ' Attempt to open the named event.
        Try
            ' Open the event with (EventWaitHandleRights.Synchronize
            ' Or EventWaitHandleRights.Modify), to wait on and 
            ' signal the named event.
            '
            ewh = EventWaitHandle.OpenExisting(ewhName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Named event does not exist.")
            doesNotExist = True
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", ex.Message)
            unauthorized = True
        End Try

        ' There are three cases: (1) The event does not exist.
        ' (2) The event exists, but the current user doesn't 
        ' have access. (3) The event exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The event does not exist, so create it.

            ' Create an access control list (ACL) that denies the
            ' current user the right to wait on or signal the 
            ' event, but allows the right to read and change
            ' security information for the event.
            '
            Dim user As String = Environment.UserDomainName _ 
                & "\" & Environment.UserName
            Dim ewhSec As New EventWaitHandleSecurity()

            Dim rule As New EventWaitHandleAccessRule(user, _
                EventWaitHandleRights.Synchronize Or _
                EventWaitHandleRights.Modify, _
                AccessControlType.Deny)
            ewhSec.AddAccessRule(rule)

            rule = New EventWaitHandleAccessRule(user, _
                EventWaitHandleRights.ReadPermissions Or _
                EventWaitHandleRights.ChangePermissions, _
                AccessControlType.Allow)
            ewhSec.AddAccessRule(rule)

            ' Create an EventWaitHandle object that represents
            ' the system event named by the constant 'ewhName', 
            ' initially signaled, with automatic reset, and with
            ' the specified security access. The Boolean value that 
            ' indicates creation of the underlying system object
            ' is placed in wasCreated.
            '
            ewh = New EventWaitHandle(True, _
                EventResetMode.AutoReset, ewhName, _
                wasCreated, ewhSec)

            ' If the named system event was created, it can be
            ' used by the current instance of this program, even 
            ' though the current user is denied access. The current
            ' program owns the event. Otherwise, exit the program.
            ' 
            If wasCreated Then
                Console.WriteLine("Created the named event.")
            Else
                Console.WriteLine("Unable to create the event.")
                Return
            End If

        ElseIf unauthorized Then

            ' Open the event to read and change the access control
            ' security. The access control security defined above
            ' allows the current user to do this.
            '
            Try
                ewh = EventWaitHandle.OpenExisting(ewhName, _
                    EventWaitHandleRights.ReadPermissions Or _
                    EventWaitHandleRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' EventWaitHandleRights.ReadPermissions.
                Dim ewhSec As EventWaitHandleSecurity = _
                    ewh.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the event must
                ' be removed.
                Dim rule As New EventWaitHandleAccessRule(user, _
                    EventWaitHandleRights.Synchronize Or _
                    EventWaitHandleRights.Modify, _
                    AccessControlType.Deny)
                ewhSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New EventWaitHandleAccessRule(user, _
                    EventWaitHandleRights.Synchronize Or _
                    EventWaitHandleRights.Modify, _
                    AccessControlType.Allow)
                ewhSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' EventWaitHandleRights.ChangePermissions.
                ewh.SetAccessControl(ewhSec)

                Console.WriteLine("Updated event security.")

                ' Open the event with (EventWaitHandleRights.Synchronize 
                ' Or EventWaitHandleRights.Modify), the rights required
                ' to wait on and signal the event.
                '
                ewh = EventWaitHandle.OpenExisting(ewhName)

            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unable to change permissions: {0}", _
                    ex.Message)
                Return
            End Try

        End If

        ' Wait on the event, and hold it until the program
        ' exits.
        '
        Try
            Console.WriteLine("Wait on the event.")
            ewh.WaitOne()
            Console.WriteLine("Event was signaled.")
            Console.WriteLine("Press the Enter key to signal the event and exit.")
            Console.ReadLine()
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", _
                ex.Message)
        Finally
            ewh.Set()
        End Try
    End Sub 
End Class 

설명

에는 name Global\ Local\ 네임 스페이스를 지정 하기 위해 또는 접두사가 추가 될 수 있습니다.The name may be prefixed with Global\ or Local\ to specify a namespace. Global네임 스페이스를 지정 하는 경우 동기화 개체를 시스템의 모든 프로세스와 공유할 수 있습니다.When the Global namespace is specified, the synchronization object may be shared with any processes on the system. 네임 스페이스를 Local 지정 하지 않은 경우에도 기본 네임 스페이스를 지정 하면 동기화 개체가 동일한 세션의 프로세스와 공유 될 수 있습니다.When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. Windows에서 세션은 로그인 세션 이며 서비스는 일반적으로 다른 비 대화형 세션에서 실행 됩니다.On Windows, a session is a login session, and services typically run in a different non-interactive session. Unix와 비슷한 운영 체제에서 각 셸에는 자체 세션이 있습니다.On Unix-like operating systems, each shell has its own session. 세션 로컬 동기화 개체는 모두 동일한 세션에서 실행 되는 부모/자식 관계를 사용 하 여 프로세스 간 동기화에 적합할 수 있습니다.Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. Windows의 synchornization 개체 이름에 대 한 자세한 내용은 개체 이름을 참조 하세요.For more information about synchornization object names on Windows, see Object Names.

요청 된 형식의 동기화 개체가 네임 스페이스에 있는 경우 기존 동기화 개체가 열립니다.If a synchronization object of the requested type exists in the namespace, the existing synchronization object is opened. 네임 스페이스에 동기화 개체가 없거나 네임 스페이스에 다른 형식의 동기화 개체가 있는 경우 WaitHandleCannotBeOpenedException 이 throw 됩니다.If a synchronization object does not exist in the namespace, or a synchronization object of a different type exists in the namespace, a WaitHandleCannotBeOpenedException is thrown.

OpenExisting메서드는 지정 된 명명 된 시스템 이벤트를 열려고 시도 합니다.The OpenExisting method tries to open the specified named system event. 아직 존재 하지 않는 시스템 이벤트를 만들려면 매개 변수가 있는 생성자 중 하나를 사용 EventWaitHandle name 합니다.To create the system event when it does not already exist, use one of the EventWaitHandle constructors that has a name parameter.

에 동일한 값을 사용 하는이 메서드를 여러 번 호출 하면 name EventWaitHandle 반환 되는 개체가 동일한 명명 된 시스템 이벤트를 나타내는 경우에도 동일한 개체가 반환 되지 않습니다.Multiple calls to this method that use the same value for name do not necessarily return the same EventWaitHandle object, even though the objects that are returned represent the same named system event.

이 메서드 오버 로드는 OpenExisting(String, EventWaitHandleRights) EventWaitHandleRights.Synchronize EventWaitHandleRights.Modify 비트 or 연산을 사용 하 여 결합 된 메서드 오버 로드를 호출 하 고 및 권한을 지정 하는 것과 같습니다.This method overload is equivalent to calling the OpenExisting(String, EventWaitHandleRights) method overload and specifying EventWaitHandleRights.Synchronize and EventWaitHandleRights.Modify rights, combined by using the bitwise OR operation.

플래그를 지정 하면 EventWaitHandleRights.Synchronize 스레드가 명명 된 시스템 이벤트에서 대기 하 고 플래그를 지정 하 여 EventWaitHandleRights.Modify 스레드에서 및 메서드를 호출할 수 Set 있습니다 Reset .Specifying the EventWaitHandleRights.Synchronize flag allows a thread to wait on the named system event, and specifying the EventWaitHandleRights.Modify flag allows a thread to call the Set and Reset methods.

추가 정보

적용 대상

OpenExisting(String, EventWaitHandleRights)

이미 있는 경우 지정한 명명된 동기화 이벤트를 원하는 보안 액세스로 엽니다.Opens the specified named synchronization event, if it already exists, with the desired security access.

public:
 static System::Threading::EventWaitHandle ^ OpenExisting(System::String ^ name, System::Security::AccessControl::EventWaitHandleRights rights);
public static System.Threading.EventWaitHandle OpenExisting (string name, System.Security.AccessControl.EventWaitHandleRights rights);
[System.Security.SecurityCritical]
public static System.Threading.EventWaitHandle OpenExisting (string name, System.Security.AccessControl.EventWaitHandleRights rights);
static member OpenExisting : string * System.Security.AccessControl.EventWaitHandleRights -> System.Threading.EventWaitHandle
[<System.Security.SecurityCritical>]
static member OpenExisting : string * System.Security.AccessControl.EventWaitHandleRights -> System.Threading.EventWaitHandle
Public Shared Function OpenExisting (name As String, rights As EventWaitHandleRights) As EventWaitHandle

매개 변수

name
String

열고 다른 프로세스와 공유할 동기화 개체의 이름입니다.The name of the synchronization object to be opened and shared with other processes. 이름은 대/소문자를 구분합니다.The name is case-sensitive.

rights
EventWaitHandleRights

원하는 보안 액세스 권한을 나타내는 열거형 값의 비트 조합입니다.A bitwise combination of the enumeration values that represent the desired security access.

반환

EventWaitHandle

명명된 시스템 이벤트를 나타내는 개체입니다.An object that represents the named system event.

특성

예외

name이 빈 문자열인 경우name is an empty string.

-또는--or-

.NET Framework에만 해당: name이 MAX_PATH(260자)보다 깁니다..NET Framework only: name is longer than MAX_PATH (260 characters).

name이(가) null인 경우.name is null.

이름이 name인 동기화 개체를 열 수 없습니다.A synchronization object with the provided name cannot be opened. 존재하지 않거나 다른 형식의 동기화 개체에 동일한 이름이 사용되었을 수 있습니다.It may not exist, or a synchronization object of a different type might have the same name. 잘못된 이름 때문에 이 예외가 throw되기도 합니다.In some cases, this exception may be thrown for invalid names.

name이 잘못되었습니다.name is invalid. 이유는 다양하며, 대표적인 이유는 운영 체제가 적용하는 일부 제한(예: 알 수 없는 접두사나 잘못된 문자)입니다.This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. 이름과 일반 접두사인 "Global" 및 "Local"은 대/소문자를 구분합니다.Note that the name and common prefixes "Global" and "Local" are case-sensitive.

-또는--or-

다른 오류가 발생했습니다.There was some other error. HResult 속성에서 자세한 정보를 확인할 수 있습니다.The HResult property may provide more information.

Windows에만 해당: name이 알 수 없는 네임스페이스를 지정했습니다.Windows only: name specified an unknown namespace. 자세한 내용은 개체 이름을 참조하세요.See Object Names for more information.

name이 너무 깁니다.The name is too long. 길이 제한은 운영 체제나 구성에 따라 달라집니다.Length restrictions may depend on the operating system or configuration.

명명된 이벤트가 존재하지만 사용자에게 필요한 보안 액세스 권한이 없는 경우The named event exists, but the user does not have the desired security access.

예제

다음 코드 예제에서는 액세스 제어 보안을 사용 하는 명명 된 시스템 이벤트의 크로스 프로세스 동작을 보여 줍니다.The following code example demonstrates the cross-process behavior of a named system event with access control security. 이 예제에서는 메서드 오버 로드를 사용 하 여 OpenExisting(String) 명명 된 이벤트의 존재 여부를 테스트 합니다.The example uses the OpenExisting(String) method overload to test for the existence of a named event.

이벤트가 존재 하지 않는 경우 현재 사용자에 게 이벤트를 사용할 수 있는 권한을 거부 하 고 이벤트에 대 한 권한을 읽고 변경할 수 있는 권한을 부여 하는 초기 소유권 및 액세스 제어 보안을 사용 하 여 생성 됩니다.If the event does not exist, it is created with initial ownership and access control security that denies the current user the right to use the event, but grants the right to read and change permissions on the event.

두 명령 창에서 컴파일된 예제를 실행 하는 경우 두 번째 복사본은에 대 한 호출에서 액세스 위반 예외를 throw 합니다 OpenExisting(String) .If you run the compiled example from two command windows, the second copy will throw an access violation exception on the call to OpenExisting(String). 예외가 catch 되 고 예제에서는 메서드 오버 로드를 사용 하 여 OpenExisting(String, EventWaitHandleRights) 사용 권한을 읽고 변경 하는 데 필요한 권한을 사용 하 여 이벤트를 기다립니다.The exception is caught, and the example uses the OpenExisting(String, EventWaitHandleRights) method overload to wait on the event with the rights needed to read and change the permissions.

사용 권한이 변경 된 후에는 이벤트를 대기 하 고 신호를 보내는 데 필요한 권한을 사용 하 여 이벤트를 엽니다.After the permissions are changed, the event is opened with the rights required to wait on it and signal it. 세 번째 명령 창에서 컴파일된 예제를 실행 하는 경우이 예제는 새 사용 권한을 사용 하 여 실행 됩니다.If you run the compiled example from a third command window, the example runs using the new permissions.

using namespace System;
using namespace System::Threading;
using namespace System::Security::AccessControl;
using namespace System::Security::Permissions;

public ref class Example
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand,Flags=SecurityPermissionFlag::UnmanagedCode)]
   static void Main()
   {
      String^ ewhName = L"EventWaitHandleExample5";

      EventWaitHandle^ ewh = nullptr;
      bool doesNotExist = false;
      bool unauthorized = false;
      
      // The value of this variable is set by the event
      // constructor. It is true if the named system event was
      // created, and false if the named event already existed.
      //
      bool wasCreated;
      
      // Attempt to open the named event.
      try
      {
         // Open the event with (EventWaitHandleRights.Synchronize
         // | EventWaitHandleRights.Modify), to wait on and
         // signal the named event.
         //
         ewh = EventWaitHandle::OpenExisting( ewhName );
      }
      catch ( WaitHandleCannotBeOpenedException^ ) 
      {
         Console::WriteLine( L"Named event does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
         unauthorized = true;
      }

      // There are three cases: (1) The event does not exist.
      // (2) The event exists, but the current user doesn't
      // have access. (3) The event exists and the user has
      // access.
      //
      if ( doesNotExist )
      {
         // The event does not exist, so create it.

         // Create an access control list (ACL) that denies the
         // current user the right to wait on or signal the
         // event, but allows the right to read and change
         // security information for the event.
         //
         String^ user = String::Concat( Environment::UserDomainName, L"\\",
            Environment::UserName );
         EventWaitHandleSecurity^ ewhSec = gcnew EventWaitHandleSecurity;
         //following constructor fails
         EventWaitHandleAccessRule^ rule = gcnew EventWaitHandleAccessRule(
            user,
            static_cast<EventWaitHandleRights>(
               EventWaitHandleRights::Synchronize | 
               EventWaitHandleRights::Modify),
            AccessControlType::Deny );
         ewhSec->AddAccessRule( rule );

         rule = gcnew EventWaitHandleAccessRule( user,
            static_cast<EventWaitHandleRights>(
               EventWaitHandleRights::ReadPermissions | 
               EventWaitHandleRights::ChangePermissions),
            AccessControlType::Allow );
         ewhSec->AddAccessRule( rule );
         
         // Create an EventWaitHandle object that represents
         // the system event named by the constant 'ewhName',
         // initially signaled, with automatic reset, and with
         // the specified security access. The Boolean value that
         // indicates creation of the underlying system object
         // is placed in wasCreated.
         //
         ewh = gcnew EventWaitHandle( true,
            EventResetMode::AutoReset,
            ewhName,
            wasCreated,
            ewhSec );
         
         // If the named system event was created, it can be
         // used by the current instance of this program, even
         // though the current user is denied access. The current
         // program owns the event. Otherwise, exit the program.
         //
         if ( wasCreated )
         {
            Console::WriteLine( L"Created the named event." );
         }
         else
         {
            Console::WriteLine( L"Unable to create the event." );
            return;
         }
      }
      else if ( unauthorized )
      {
         // Open the event to read and change the access control
         // security. The access control security defined above
         // allows the current user to do this.
         //
         try
         {
            ewh = EventWaitHandle::OpenExisting( ewhName, 
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::ReadPermissions |
                  EventWaitHandleRights::ChangePermissions) );
            
            // Get the current ACL. This requires
            // EventWaitHandleRights.ReadPermissions.
            EventWaitHandleSecurity^ ewhSec = ewh->GetAccessControl();
            String^ user = String::Concat( Environment::UserDomainName, L"\\",
               Environment::UserName );
            
            // First, the rule that denied the current user
            // the right to enter and release the event must
            // be removed.
            EventWaitHandleAccessRule^ rule = gcnew EventWaitHandleAccessRule(
               user,
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::Synchronize |
                  EventWaitHandleRights::Modify),
               AccessControlType::Deny );
            ewhSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew EventWaitHandleAccessRule( user,
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::Synchronize |
                  EventWaitHandleRights::Modify),
               AccessControlType::Allow );
            ewhSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // EventWaitHandleRights.ChangePermissions.
            ewh->SetAccessControl( ewhSec );
            Console::WriteLine( L"Updated event security." );
            
            // Open the event with (EventWaitHandleRights.Synchronize
            // | EventWaitHandleRights.Modify), the rights required
            // to wait on and signal the event.
            //
            ewh = EventWaitHandle::OpenExisting( ewhName );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine( L"Unable to change permissions: {0}",
               ex->Message );
            return;
         }

      }
      
      // Wait on the event, and hold it until the program
      // exits.
      //
      try
      {
         Console::WriteLine( L"Wait on the event." );
         ewh->WaitOne();
         Console::WriteLine( L"Event was signaled." );
         Console::WriteLine( L"Press the Enter key to signal the event and exit." );
         Console::ReadLine();
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
      }
      finally
      {
         ewh->Set();
      }
   }
};

int main()
{
   Example::Main();
}
using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string ewhName = "EventWaitHandleExample5";

        EventWaitHandle ewh = null;
        bool doesNotExist = false;
        bool unauthorized = false;

        // The value of this variable is set by the event
        // constructor. It is true if the named system event was
        // created, and false if the named event already existed.
        //
        bool wasCreated;

        // Attempt to open the named event.
        try
        {
            // Open the event with (EventWaitHandleRights.Synchronize
            // | EventWaitHandleRights.Modify), to wait on and 
            // signal the named event.
            //
            ewh = EventWaitHandle.OpenExisting(ewhName);
        }
        catch (WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Named event does not exist.");
            doesNotExist = true;
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // There are three cases: (1) The event does not exist.
        // (2) The event exists, but the current user doesn't 
        // have access. (3) The event exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The event does not exist, so create it.

            // Create an access control list (ACL) that denies the
            // current user the right to wait on or signal the 
            // event, but allows the right to read and change
            // security information for the event.
            //
            string user = Environment.UserDomainName + "\\"
                + Environment.UserName;
            EventWaitHandleSecurity ewhSec = 
                new EventWaitHandleSecurity();

            EventWaitHandleAccessRule rule = 
                new EventWaitHandleAccessRule(user, 
                    EventWaitHandleRights.Synchronize | 
                    EventWaitHandleRights.Modify, 
                    AccessControlType.Deny);
            ewhSec.AddAccessRule(rule);

            rule = new EventWaitHandleAccessRule(user, 
                EventWaitHandleRights.ReadPermissions | 
                EventWaitHandleRights.ChangePermissions, 
                AccessControlType.Allow);
            ewhSec.AddAccessRule(rule);

            // Create an EventWaitHandle object that represents
            // the system event named by the constant 'ewhName', 
            // initially signaled, with automatic reset, and with
            // the specified security access. The Boolean value that 
            // indicates creation of the underlying system object
            // is placed in wasCreated.
            //
            ewh = new EventWaitHandle(true, 
                EventResetMode.AutoReset, 
                ewhName, 
                out wasCreated, 
                ewhSec);

            // If the named system event was created, it can be
            // used by the current instance of this program, even 
            // though the current user is denied access. The current
            // program owns the event. Otherwise, exit the program.
            // 
            if (wasCreated)
            {
                Console.WriteLine("Created the named event.");
            }
            else
            {
                Console.WriteLine("Unable to create the event.");
                return;
            }
        }
        else if (unauthorized)
        {
            // Open the event to read and change the access control
            // security. The access control security defined above
            // allows the current user to do this.
            //
            try
            {
                ewh = EventWaitHandle.OpenExisting(ewhName, 
                    EventWaitHandleRights.ReadPermissions | 
                    EventWaitHandleRights.ChangePermissions);

                // Get the current ACL. This requires 
                // EventWaitHandleRights.ReadPermissions.
                EventWaitHandleSecurity ewhSec = ewh.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\"
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the event must
                // be removed.
                EventWaitHandleAccessRule rule = 
                    new EventWaitHandleAccessRule(user, 
                        EventWaitHandleRights.Synchronize | 
                        EventWaitHandleRights.Modify, 
                        AccessControlType.Deny);
                ewhSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new EventWaitHandleAccessRule(user, 
                    EventWaitHandleRights.Synchronize | 
                    EventWaitHandleRights.Modify, 
                    AccessControlType.Allow);
                ewhSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // EventWaitHandleRights.ChangePermissions.
                ewh.SetAccessControl(ewhSec);

                Console.WriteLine("Updated event security.");

                // Open the event with (EventWaitHandleRights.Synchronize 
                // | EventWaitHandleRights.Modify), the rights required
                // to wait on and signal the event.
                //
                ewh = EventWaitHandle.OpenExisting(ewhName);
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}",
                    ex.Message);
                return;
            }
        }

        // Wait on the event, and hold it until the program
        // exits.
        //
        try
        {
            Console.WriteLine("Wait on the event.");
            ewh.WaitOne();
            Console.WriteLine("Event was signaled.");
            Console.WriteLine("Press the Enter key to signal the event and exit.");
            Console.ReadLine();
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
        }
        finally
        {
            ewh.Set();
        }
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const ewhName As String = "EventWaitHandleExample5"

        Dim ewh As EventWaitHandle = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

        ' The value of this variable is set by the event
        ' constructor. It is True if the named system event was
        ' created, and False if the named event already existed.
        '
        Dim wasCreated As Boolean

        ' Attempt to open the named event.
        Try
            ' Open the event with (EventWaitHandleRights.Synchronize
            ' Or EventWaitHandleRights.Modify), to wait on and 
            ' signal the named event.
            '
            ewh = EventWaitHandle.OpenExisting(ewhName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Named event does not exist.")
            doesNotExist = True
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", ex.Message)
            unauthorized = True
        End Try

        ' There are three cases: (1) The event does not exist.
        ' (2) The event exists, but the current user doesn't 
        ' have access. (3) The event exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The event does not exist, so create it.

            ' Create an access control list (ACL) that denies the
            ' current user the right to wait on or signal the 
            ' event, but allows the right to read and change
            ' security information for the event.
            '
            Dim user As String = Environment.UserDomainName _ 
                & "\" & Environment.UserName
            Dim ewhSec As New EventWaitHandleSecurity()

            Dim rule As New EventWaitHandleAccessRule(user, _
                EventWaitHandleRights.Synchronize Or _
                EventWaitHandleRights.Modify, _
                AccessControlType.Deny)
            ewhSec.AddAccessRule(rule)

            rule = New EventWaitHandleAccessRule(user, _
                EventWaitHandleRights.ReadPermissions Or _
                EventWaitHandleRights.ChangePermissions, _
                AccessControlType.Allow)
            ewhSec.AddAccessRule(rule)

            ' Create an EventWaitHandle object that represents
            ' the system event named by the constant 'ewhName', 
            ' initially signaled, with automatic reset, and with
            ' the specified security access. The Boolean value that 
            ' indicates creation of the underlying system object
            ' is placed in wasCreated.
            '
            ewh = New EventWaitHandle(True, _
                EventResetMode.AutoReset, ewhName, _
                wasCreated, ewhSec)

            ' If the named system event was created, it can be
            ' used by the current instance of this program, even 
            ' though the current user is denied access. The current
            ' program owns the event. Otherwise, exit the program.
            ' 
            If wasCreated Then
                Console.WriteLine("Created the named event.")
            Else
                Console.WriteLine("Unable to create the event.")
                Return
            End If

        ElseIf unauthorized Then

            ' Open the event to read and change the access control
            ' security. The access control security defined above
            ' allows the current user to do this.
            '
            Try
                ewh = EventWaitHandle.OpenExisting(ewhName, _
                    EventWaitHandleRights.ReadPermissions Or _
                    EventWaitHandleRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' EventWaitHandleRights.ReadPermissions.
                Dim ewhSec As EventWaitHandleSecurity = _
                    ewh.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the event must
                ' be removed.
                Dim rule As New EventWaitHandleAccessRule(user, _
                    EventWaitHandleRights.Synchronize Or _
                    EventWaitHandleRights.Modify, _
                    AccessControlType.Deny)
                ewhSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New EventWaitHandleAccessRule(user, _
                    EventWaitHandleRights.Synchronize Or _
                    EventWaitHandleRights.Modify, _
                    AccessControlType.Allow)
                ewhSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' EventWaitHandleRights.ChangePermissions.
                ewh.SetAccessControl(ewhSec)

                Console.WriteLine("Updated event security.")

                ' Open the event with (EventWaitHandleRights.Synchronize 
                ' Or EventWaitHandleRights.Modify), the rights required
                ' to wait on and signal the event.
                '
                ewh = EventWaitHandle.OpenExisting(ewhName)

            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unable to change permissions: {0}", _
                    ex.Message)
                Return
            End Try

        End If

        ' Wait on the event, and hold it until the program
        ' exits.
        '
        Try
            Console.WriteLine("Wait on the event.")
            ewh.WaitOne()
            Console.WriteLine("Event was signaled.")
            Console.WriteLine("Press the Enter key to signal the event and exit.")
            Console.ReadLine()
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", _
                ex.Message)
        Finally
            ewh.Set()
        End Try
    End Sub 
End Class 

설명

에는 name Global\ Local\ 네임 스페이스를 지정 하기 위해 또는 접두사가 추가 될 수 있습니다.The name may be prefixed with Global\ or Local\ to specify a namespace. Global네임 스페이스를 지정 하는 경우 동기화 개체를 시스템의 모든 프로세스와 공유할 수 있습니다.When the Global namespace is specified, the synchronization object may be shared with any processes on the system. 네임 스페이스를 Local 지정 하지 않은 경우에도 기본 네임 스페이스를 지정 하면 동기화 개체가 동일한 세션의 프로세스와 공유 될 수 있습니다.When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. Windows에서 세션은 로그인 세션 이며 서비스는 일반적으로 다른 비 대화형 세션에서 실행 됩니다.On Windows, a session is a login session, and services typically run in a different non-interactive session. Unix와 비슷한 운영 체제에서 각 셸에는 자체 세션이 있습니다.On Unix-like operating systems, each shell has its own session. 세션 로컬 동기화 개체는 모두 동일한 세션에서 실행 되는 부모/자식 관계를 사용 하 여 프로세스 간 동기화에 적합할 수 있습니다.Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. Windows의 synchornization 개체 이름에 대 한 자세한 내용은 개체 이름을 참조 하세요.For more information about synchornization object names on Windows, see Object Names.

요청 된 형식의 동기화 개체가 네임 스페이스에 있는 경우 기존 동기화 개체가 열립니다.If a synchronization object of the requested type exists in the namespace, the existing synchronization object is opened. 네임 스페이스에 동기화 개체가 없거나 네임 스페이스에 다른 형식의 동기화 개체가 있는 경우 WaitHandleCannotBeOpenedException 이 throw 됩니다.If a synchronization object does not exist in the namespace, or a synchronization object of a different type exists in the namespace, a WaitHandleCannotBeOpenedException is thrown.

rights매개 변수는 EventWaitHandleRights.Synchronize 스레드가 이벤트에서 대기 하도록 허용 하는 플래그와 EventWaitHandleRights.Modify 스레드가 및 메서드를 호출할 수 있도록 하는 플래그를 포함 해야 합니다 Set Reset .The rights parameter must include the EventWaitHandleRights.Synchronize flag to allow threads to wait on the event, and the EventWaitHandleRights.Modify flag to allow threads to call the Set and Reset methods.

OpenExisting메서드는 기존 명명 된 시스템 이벤트를 열려고 시도 합니다.The OpenExisting method tries to open an existing named system event. 아직 존재 하지 않는 시스템 이벤트를 만들려면 매개 변수가 있는 생성자 중 하나를 사용 EventWaitHandle name 합니다.To create the system event when it does not already exist, use one of the EventWaitHandle constructors that has a name parameter.

에 동일한 값을 사용 하는이 메서드를 여러 번 호출 하면 name EventWaitHandle 반환 되는 개체가 동일한 명명 된 시스템 이벤트를 나타내는 경우에도 동일한 개체가 반환 되지 않습니다.Multiple calls to this method that use the same value for name do not necessarily return the same EventWaitHandle object, even though the objects that are returned represent the same named system event.

추가 정보

적용 대상