EventWaitHandle.OpenExisting 方法

定义

打开指定名称为同步事件(如果已经存在).

重载

OpenExisting(String)

打开指定名称为同步事件(如果已经存在)。

OpenExisting(String, EventWaitHandleRights)

用安全访问权限打开指定名称为同步事件(如果已经存在)。

OpenExisting(String)

Source:
EventWaitHandle.cs
Source:
EventWaitHandle.cs
Source:
EventWaitHandle.cs

打开指定名称为同步事件(如果已经存在)。

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

要与其他进程打开和共享的同步对象的名称。 该名称区分大小写。 反斜杠字符 (\) 是保留的,只能用于指定命名空间。 有关命名空间的详细信息,请参阅备注部分。 根据操作系统,名称可能会有进一步的限制。 例如,在基于 Unix 的操作系统上,排除命名空间后的名称必须是有效的文件名。

返回

一个对象,表示已命名的系统事件。

属性

例外

无法打开具有提供的 name 的同步对象。 该对象可能不存在,或者不同类型的同步对象可能具有相同的名称。 在某些情况下,可能会因名称无效而引发此异常。

name 是一个空字符串。

仅限 .NET Framework:name 的长度超过 MAX_PATH(260 个字符)。

name 上声明的默认值为 null

name 无效。 导致这种情况的原因有很多,包括操作系统可能会施加的一些限制,例如未知前缀或无效字符。 请注意,名称和通用前缀“Global\”和“Local\”区分大小写。

还有一些其他错误。 HResult 属性可能提供更多信息。

仅限 Windows:name 指定了未知命名空间。 有关详细信息,请参阅对象名称

name 太长。 长度限制可能取决于操作系统或配置。

已命名的事件存在,但用户不具备使用它所需的安全访问权限。

注解

name可以使用 或 Local\ 作为Global\前缀,以指定命名空间。 Global指定命名空间后,可以与系统上的任何进程共享同步对象。 Local指定命名空间时(未指定命名空间时也是默认值),可以与同一会话中的进程共享同步对象。 在 Windows 上,会话是登录会话,服务通常在不同的非交互式会话中运行。 在类似于 Unix 的操作系统上,每个 shell 都有其自己的会话。 会话本地同步对象可能适合用于使用父/子关系(在这些进程都在同一会话中运行)之间进行同步。 有关 Windows 上的同步对象名称的详细信息,请参阅 对象名称

如果命名空间中存在所请求类型的同步对象,则会打开现有的同步对象。 如果命名空间中不存在同步对象,或者命名空间中存在不同类型的同步对象, WaitHandleCannotBeOpenedException 则会引发 。

方法 OpenExisting 尝试打开指定的命名系统事件。 若要在系统事件尚不存在时创建它,请使用具有 参数的 EventWaitHandle 构造函数之一 name

对此方法使用相同值的 name 多次调用不一定返回相同的 EventWaitHandle 对象,即使返回的对象表示相同的命名系统事件。

在 .NET Framework 中,此方法重载等效于调用 System.Threading.EventWaitHandle.OpenExisting (System.String,System.Security.AccessControl.EventWaitHandleRights) 方法重载和指定 EventWaitHandleRights.SynchronizeEventWaitHandleRights.Modify 权限,并使用按 OR 位操作组合。

指定 EventWaitHandleRights.Synchronize 标志允许线程等待命名的系统事件,而 EventWaitHandleRights.Modify 指定标志允许线程调用 SetReset 方法。

另请参阅

适用于

OpenExisting(String, EventWaitHandleRights)

用安全访问权限打开指定名称为同步事件(如果已经存在)。

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

要与其他进程打开和共享的同步对象的名称。 该名称区分大小写。 反斜杠字符 (\) 是保留的,只能用于指定命名空间。 有关命名空间的详细信息,请参阅备注部分。 根据操作系统,名称可能会有进一步的限制。 例如,在基于 Unix 的操作系统上,排除命名空间后的名称必须是有效的文件名。

rights
EventWaitHandleRights

表示所需的安全访问权限的枚举值的按位组合。

返回

一个对象,表示已命名的系统事件。

属性

例外

name 是一个空字符串。

仅限 .NET Framework:name 的长度超过 MAX_PATH(260 个字符)。

name 上声明的默认值为 null

无法打开具有提供的 name 的同步对象。 该对象可能不存在,或者不同类型的同步对象可能具有相同的名称。 在某些情况下,可能会因名称无效而引发此异常。

name 无效。 导致这种情况的原因有很多,包括操作系统可能会施加的一些限制,例如未知前缀或无效字符。 请注意,名称和通用前缀“Global\”和“Local\”区分大小写。

还有一些其他错误。 HResult 属性可能提供更多信息。

仅限 Windows:name 指定了未知命名空间。 有关详细信息,请参阅对象名称

name 太长。 长度限制可能取决于操作系统或配置。

命名事件存在,但用户不具有所需的安全访问权限。

示例

以下代码示例演示具有访问控制安全性的命名系统事件的跨进程行为。 该示例使用 OpenExisting(String) 方法重载来测试命名事件是否存在。

如果该事件不存在,则会使用初始所有权和访问控制安全性创建该事件,该安全性将拒绝当前用户使用该事件的权利,但授予对事件进行读取和更改权限的权限。

如果从两个命令窗口运行编译的示例,则第二个副本将在调用 OpenExisting(String)时引发访问冲突异常。 捕获异常,该示例使用 OpenExisting(String, EventWaitHandleRights) 方法重载等待具有读取和更改权限所需的权限的事件。

更改权限后,事件将打开,其中包含等待它并发出信号所需的权限。 如果从第三个命令窗口运行已编译的示例,则使用新权限运行该示例。

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可以使用 或 Local\ 作为Global\前缀,以指定命名空间。 Global指定命名空间后,可以与系统上的任何进程共享同步对象。 Local指定命名空间时(未指定命名空间时也是默认值),可以与同一会话中的进程共享同步对象。 在 Windows 上,会话是登录会话,服务通常在不同的非交互式会话中运行。 在类似于 Unix 的操作系统上,每个 shell 都有其自己的会话。 会话本地同步对象可能适合用于使用父/子关系(在这些进程都在同一会话中运行)之间进行同步。 有关 Windows 上的同步对象名称的详细信息,请参阅 对象名称

如果命名空间中存在所请求类型的同步对象,则会打开现有的同步对象。 如果命名空间中不存在同步对象,或者命名空间中存在不同类型的同步对象, WaitHandleCannotBeOpenedException 则会引发 。

参数 rights 必须包含 EventWaitHandleRights.Synchronize 允许线程等待事件的标志,以及 EventWaitHandleRights.Modify 允许线程调用 SetReset 方法的标志。

方法 OpenExisting 尝试打开现有的命名系统事件。 若要在系统事件尚不存在时创建它,请使用具有 参数的 EventWaitHandle 构造函数之一 name

对此方法使用相同值的 name 多次调用不一定返回相同的 EventWaitHandle 对象,即使返回的对象表示相同的命名系统事件。

另请参阅

适用于