共用方式為


EventWaitHandle.OpenExisting 方法

定義

開啟指定的具名同步處理事件 (如果已經存在)。

多載

OpenExisting(String)

開啟指定的具名同步處理事件 (如果已經存在)。

OpenExisting(String, EventWaitHandleRights)

使用所需的安全性存取權,開啟指定的具名同步處理事件 (如果已經存在)。

OpenExisting(String)

來源:
EventWaitHandle.cs
來源:
EventWaitHandle.cs
來源:
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前面可能會加上 Global\Local\ ,以指定命名空間。 Global指定命名空間時,同步處理物件可能會與系統上的任何進程共用。 Local指定命名空間時,這也是未指定命名空間時的預設值,同步處理物件可能會與相同會話中的進程共用。 在 Windows 上,會話是登入工作階段,服務通常會在不同的非互動式會話中執行。 在類似 Unix 的作業系統上,每個殼層都有自己的會話。 會話本機同步處理物件可能適用於在進程與父/子關聯性之間同步處理,其中它們全都在相同會話中執行。 如需 Windows 上同步處理物件名稱的詳細資訊,請參閱 物件名稱

如果命名空間中存在要求的同步處理物件,則會開啟現有的同步處理物件。 如果命名空間中不存在同步處理物件,或命名空間中存在不同類型的同步處理物件, WaitHandleCannotBeOpenedException 則會擲回 。

方法 OpenExisting 會嘗試開啟指定的具名系統事件。 若要在系統事件不存在時建立系統事件,請使用其中一個name具有 參數的EventWaitHandle建構函式。

對這個方法使用相同值的 name 多個呼叫不一定傳回相同的 EventWaitHandle 物件,即使傳回的物件代表相同的具名系統事件也一樣。

在 .NET Framework 中,這個方法多載相當於呼叫 System.Threading.EventWaitHandle.OpenExisting (System.String、System.Security.AccessControl.EventWaitHandleRights) 方法多載,並使用位OR運算結合並指定EventWaitHandleRights.SynchronizeEventWaitHandleRights.Modify許可權。

指定 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前面可能會加上 Global\Local\ ,以指定命名空間。 Global指定命名空間時,同步處理物件可能會與系統上的任何進程共用。 Local指定命名空間時,這也是未指定命名空間時的預設值,同步處理物件可能會與相同會話中的進程共用。 在 Windows 上,會話是登入工作階段,服務通常會在不同的非互動式會話中執行。 在類似 Unix 的作業系統上,每個殼層都有自己的會話。 會話本機同步處理物件可能適用於在進程與父/子關聯性之間同步處理,其中它們全都在相同會話中執行。 如需 Windows 上同步處理物件名稱的詳細資訊,請參閱 物件名稱

如果命名空間中存在要求的同步處理物件,則會開啟現有的同步處理物件。 如果命名空間中不存在同步處理物件,或命名空間中存在不同類型的同步處理物件, WaitHandleCannotBeOpenedException 則會擲回 。

參數 rights 必須包含 EventWaitHandleRights.Synchronize 旗標,以允許線程等候事件,以及 EventWaitHandleRights.Modify 允許線程呼叫 SetReset 方法的旗標。

方法 OpenExisting 會嘗試開啟現有的具名系統事件。 若要在系統事件不存在時建立系統事件,請使用其中一個name具有 參數的EventWaitHandle建構函式。

對這個方法使用相同值的 name 多個呼叫不一定傳回相同的 EventWaitHandle 物件,即使傳回的物件代表相同的具名系統事件也一樣。

另請參閱

適用於