EventWaitHandle 构造函数

定义

初始化 EventWaitHandle 类的新实例。Initializes a new instance of the EventWaitHandle class.

重载

EventWaitHandle(Boolean, EventResetMode)

初始化 EventWaitHandle 类的新实例,并指定等待句柄最初是否处于终止状态,以及它是自动重置还是手动重置。Initializes a new instance of the EventWaitHandle class, specifying whether the wait handle is initially signaled, and whether it resets automatically or manually.

EventWaitHandle(Boolean, EventResetMode, String)

初始化 EventWaitHandle 类的新实例,并指定在此调用后创建的等待句柄最初是否处于终止状态,它是自动重置还是手动重置,以及系统同步事件的名称。Initializes a new instance of the EventWaitHandle class, specifying whether the wait handle is initially signaled if created as a result of this call, whether it resets automatically or manually, and the name of a system synchronization event.

EventWaitHandle(Boolean, EventResetMode, String, Boolean)

初始化 EventWaitHandle 类的新实例,指定如果将等待句柄作为此调用的结果而创建,最初是否通过信号通知此句柄;指定是否自动或手动重置系统同步事件的名称,以及一个布尔变量,在调用后其值指示是否创建了命名的系统事件。Initializes a new instance of the EventWaitHandle class, specifying whether the wait handle is initially signaled if created as a result of this call, whether it resets automatically or manually, the name of a system synchronization event, and a Boolean variable whose value after the call indicates whether the named system event was created.

EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity)

初始化 EventWaitHandle 类的新实例,指定如果等待句柄作为此调用的结果而创建,最初是否通过信号通知此句柄;指定是否自动或手动重置系统同步事件的名称和布尔变量,其值在该调用后将指示是否创建了已命名系统事件,以及是否将访问控制安全性应用到命名事件(如果已创建该事件)。Initializes a new instance of the EventWaitHandle class, specifying whether the wait handle is initially signaled if created as a result of this call, whether it resets automatically or manually, the name of a system synchronization event, a Boolean variable whose value after the call indicates whether the named system event was created, and the access control security to be applied to the named event if it is created.

EventWaitHandle(Boolean, EventResetMode)

初始化 EventWaitHandle 类的新实例,并指定等待句柄最初是否处于终止状态,以及它是自动重置还是手动重置。Initializes a new instance of the EventWaitHandle class, specifying whether the wait handle is initially signaled, and whether it resets automatically or manually.

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode);
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode)

参数

initialState
Boolean

如果为 true,则将初始状态设置为终止;如果为 false,则将初始状态设置为非终止。true to set the initial state to signaled; false to set it to nonsignaled.

mode
EventResetMode

其中一个 EventResetMode 值,它确定是自动还是手动重置事件。One of the EventResetMode values that determines whether the event resets automatically or manually.

示例

下面的代码示例使用SignalAndWait(WaitHandle, WaitHandle)方法重载,以允许主线程向阻止的线程发出信号,并等待线程完成任务。The following code example uses the SignalAndWait(WaitHandle, WaitHandle) method overload to allow the main thread to signal a blocked thread and then wait until the thread finishes a task.

该示例启动五个线程,并允许它们阻止EventWaitHandle EventResetMode.AutoReset使用标志创建的,然后在每次用户按 ENTER 键时释放一个线程。The example starts five threads and allows them to block on an EventWaitHandle created with the EventResetMode.AutoReset flag, then releases one thread each time the user presses ENTER key. 然后,该示例将另一线程排队,并通过使用EventWaitHandle EventResetMode.ManualReset标志创建的所有线程释放它们。The example then queues another five threads and releases them all using an EventWaitHandle created with the EventResetMode.ManualReset flag.

using namespace System;
using namespace System::Threading;

public ref class Example
{
private:
   // The EventWaitHandle used to demonstrate the difference
   // between AutoReset and ManualReset synchronization events.
   //
   static EventWaitHandle^ ewh;

   // A counter to make sure all threads are started and
   // blocked before any are released. A Long is used to show
   // the use of the 64-bit Interlocked methods.
   //
   static __int64 threadCount = 0;

   // An AutoReset event that allows the main thread to block
   // until an exiting thread has decremented the count.
   //
   static EventWaitHandle^ clearCount =
      gcnew EventWaitHandle( false,EventResetMode::AutoReset );

public:
   [MTAThread]
   static void main()
   {
      // Create an AutoReset EventWaitHandle.
      //
      ewh = gcnew EventWaitHandle( false,EventResetMode::AutoReset );
      
      // Create and start five numbered threads. Use the
      // ParameterizedThreadStart delegate, so the thread
      // number can be passed as an argument to the Start
      // method.
      for ( int i = 0; i <= 4; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( ThreadProc ) );
         t->Start( i );
      }
      
      // Wait until all the threads have started and blocked.
      // When multiple threads use a 64-bit value on a 32-bit
      // system, you must access the value through the
      // Interlocked class to guarantee thread safety.
      //
      while ( Interlocked::Read( threadCount ) < 5 )
      {
         Thread::Sleep( 500 );
      }

      // Release one thread each time the user presses ENTER,
      // until all threads have been released.
      //
      while ( Interlocked::Read( threadCount ) > 0 )
      {
         Console::WriteLine( L"Press ENTER to release a waiting thread." );
         Console::ReadLine();
         
         // SignalAndWait signals the EventWaitHandle, which
         // releases exactly one thread before resetting,
         // because it was created with AutoReset mode.
         // SignalAndWait then blocks on clearCount, to
         // allow the signaled thread to decrement the count
         // before looping again.
         //
         WaitHandle::SignalAndWait( ewh, clearCount );
      }
      Console::WriteLine();
      
      // Create a ManualReset EventWaitHandle.
      //
      ewh = gcnew EventWaitHandle( false,EventResetMode::ManualReset );
      
      // Create and start five more numbered threads.
      //
      for ( int i = 0; i <= 4; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( ThreadProc ) );
         t->Start( i );
      }
      
      // Wait until all the threads have started and blocked.
      //
      while ( Interlocked::Read( threadCount ) < 5 )
      {
         Thread::Sleep( 500 );
      }

      // Because the EventWaitHandle was created with
      // ManualReset mode, signaling it releases all the
      // waiting threads.
      //
      Console::WriteLine( L"Press ENTER to release the waiting threads." );
      Console::ReadLine();
      ewh->Set();

   }

   static void ThreadProc( Object^ data )
   {
      int index = static_cast<Int32>(data);

      Console::WriteLine( L"Thread {0} blocks.", data );
      // Increment the count of blocked threads.
      Interlocked::Increment( threadCount );
      
      // Wait on the EventWaitHandle.
      ewh->WaitOne();

      Console::WriteLine( L"Thread {0} exits.", data );
      // Decrement the count of blocked threads.
      Interlocked::Decrement( threadCount );
      
      // After signaling ewh, the main thread blocks on
      // clearCount until the signaled thread has
      // decremented the count. Signal it now.
      //
      clearCount->Set();
   }
};
using System;
using System.Threading;

public class Example
{
    // The EventWaitHandle used to demonstrate the difference
    // between AutoReset and ManualReset synchronization events.
    //
    private static EventWaitHandle ewh;

    // A counter to make sure all threads are started and
    // blocked before any are released. A Long is used to show
    // the use of the 64-bit Interlocked methods.
    //
    private static long threadCount = 0;

    // An AutoReset event that allows the main thread to block
    // until an exiting thread has decremented the count.
    //
    private static EventWaitHandle clearCount = 
        new EventWaitHandle(false, EventResetMode.AutoReset);

    [MTAThread]
    public static void Main()
    {
        // Create an AutoReset EventWaitHandle.
        //
        ewh = new EventWaitHandle(false, EventResetMode.AutoReset);

        // Create and start five numbered threads. Use the
        // ParameterizedThreadStart delegate, so the thread
        // number can be passed as an argument to the Start 
        // method.
        for (int i = 0; i <= 4; i++)
        {
            Thread t = new Thread(
                new ParameterizedThreadStart(ThreadProc)
            );
            t.Start(i);
        }

        // Wait until all the threads have started and blocked.
        // When multiple threads use a 64-bit value on a 32-bit
        // system, you must access the value through the
        // Interlocked class to guarantee thread safety.
        //
        while (Interlocked.Read(ref threadCount) < 5)
        {
            Thread.Sleep(500);
        }

        // Release one thread each time the user presses ENTER,
        // until all threads have been released.
        //
        while (Interlocked.Read(ref threadCount) > 0)
        {
            Console.WriteLine("Press ENTER to release a waiting thread.");
            Console.ReadLine();

            // SignalAndWait signals the EventWaitHandle, which
            // releases exactly one thread before resetting, 
            // because it was created with AutoReset mode. 
            // SignalAndWait then blocks on clearCount, to 
            // allow the signaled thread to decrement the count
            // before looping again.
            //
            WaitHandle.SignalAndWait(ewh, clearCount);
        }
        Console.WriteLine();

        // Create a ManualReset EventWaitHandle.
        //
        ewh = new EventWaitHandle(false, EventResetMode.ManualReset);

        // Create and start five more numbered threads.
        //
        for(int i=0; i<=4; i++)
        {
            Thread t = new Thread(
                new ParameterizedThreadStart(ThreadProc)
            );
            t.Start(i);
        }

        // Wait until all the threads have started and blocked.
        //
        while (Interlocked.Read(ref threadCount) < 5)
        {
            Thread.Sleep(500);
        }

        // Because the EventWaitHandle was created with
        // ManualReset mode, signaling it releases all the
        // waiting threads.
        //
        Console.WriteLine("Press ENTER to release the waiting threads.");
        Console.ReadLine();
        ewh.Set();
        
    }

    public static void ThreadProc(object data)
    {
        int index = (int) data;

        Console.WriteLine("Thread {0} blocks.", data);
        // Increment the count of blocked threads.
        Interlocked.Increment(ref threadCount);

        // Wait on the EventWaitHandle.
        ewh.WaitOne();

        Console.WriteLine("Thread {0} exits.", data);
        // Decrement the count of blocked threads.
        Interlocked.Decrement(ref threadCount);

        // After signaling ewh, the main thread blocks on
        // clearCount until the signaled thread has 
        // decremented the count. Signal it now.
        //
        clearCount.Set();
    }
}
Imports System.Threading

Public Class Example

    ' The EventWaitHandle used to demonstrate the difference
    ' between AutoReset and ManualReset synchronization events.
    '
    Private Shared ewh As EventWaitHandle

    ' A counter to make sure all threads are started and
    ' blocked before any are released. A Long is used to show
    ' the use of the 64-bit Interlocked methods.
    '
    Private Shared threadCount As Long = 0

    ' An AutoReset event that allows the main thread to block
    ' until an exiting thread has decremented the count.
    '
    Private Shared clearCount As New EventWaitHandle(False, _
        EventResetMode.AutoReset)

    <MTAThread> _
    Public Shared Sub Main()

        ' Create an AutoReset EventWaitHandle.
        '
        ewh = New EventWaitHandle(False, EventResetMode.AutoReset)

        ' Create and start five numbered threads. Use the
        ' ParameterizedThreadStart delegate, so the thread
        ' number can be passed as an argument to the Start 
        ' method.
        For i As Integer = 0 To 4
            Dim t As New Thread(AddressOf ThreadProc)
            t.Start(i)
        Next i

        ' Wait until all the threads have started and blocked.
        ' When multiple threads use a 64-bit value on a 32-bit
        ' system, you must access the value through the
        ' Interlocked class to guarantee thread safety.
        '
        While Interlocked.Read(threadCount) < 5
            Thread.Sleep(500)
        End While

        ' Release one thread each time the user presses ENTER,
        ' until all threads have been released.
        '
        While Interlocked.Read(threadCount) > 0
            Console.WriteLine("Press ENTER to release a waiting thread.")
            Console.ReadLine()

            ' SignalAndWait signals the EventWaitHandle, which
            ' releases exactly one thread before resetting, 
            ' because it was created with AutoReset mode. 
            ' SignalAndWait then blocks on clearCount, to 
            ' allow the signaled thread to decrement the count
            ' before looping again.
            '
            WaitHandle.SignalAndWait(ewh, clearCount)
        End While
        Console.WriteLine()

        ' Create a ManualReset EventWaitHandle.
        '
        ewh = New EventWaitHandle(False, EventResetMode.ManualReset)

        ' Create and start five more numbered threads.
        '
        For i As Integer = 0 To 4
            Dim t As New Thread(AddressOf ThreadProc)
            t.Start(i)
        Next i

        ' Wait until all the threads have started and blocked.
        '
        While Interlocked.Read(threadCount) < 5
            Thread.Sleep(500)
        End While

        ' Because the EventWaitHandle was created with
        ' ManualReset mode, signaling it releases all the
        ' waiting threads.
        '
        Console.WriteLine("Press ENTER to release the waiting threads.")
        Console.ReadLine()
        ewh.Set()
        
    End Sub

    Public Shared Sub ThreadProc(ByVal data As Object)
        Dim index As Integer = CInt(data)

        Console.WriteLine("Thread {0} blocks.", data)
        ' Increment the count of blocked threads.
        Interlocked.Increment(threadCount)

        ' Wait on the EventWaitHandle.
        ewh.WaitOne()

        Console.WriteLine("Thread {0} exits.", data)
        ' Decrement the count of blocked threads.
        Interlocked.Decrement(threadCount)

        ' After signaling ewh, the main thread blocks on
        ' clearCount until the signaled thread has 
        ' decremented the count. Signal it now.
        '
        clearCount.Set()
    End Sub
End Class

注解

如果事件的初始状态为非终止,则等待事件的线程将会阻止。If the initial state of the event is nonsignaled, threads that wait on the event will block. 如果初始状态为 "已终止" 并且ManualResetmode指定了标志,则等待事件的线程不会阻塞。If the initial state is signaled, and the ManualReset flag is specified for mode, threads that wait on the event will not block. 如果初始状态为 "已终止" modeAutoReset并且为,则将立即释放等待事件的第一个线程,在此之后,事件将被重置,后续线程将被阻止。If the initial state is signaled, and mode is AutoReset, the first thread that waits on the event will be released immediately, after which the event will reset, and subsequent threads will block.

另请参阅

EventWaitHandle(Boolean, EventResetMode, String)

初始化 EventWaitHandle 类的新实例,并指定在此调用后创建的等待句柄最初是否处于终止状态,它是自动重置还是手动重置,以及系统同步事件的名称。Initializes a new instance of the EventWaitHandle class, specifying whether the wait handle is initially signaled if created as a result of this call, whether it resets automatically or manually, and the name of a system synchronization event.

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode, System::String ^ name);
[System.Security.SecurityCritical]
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name);
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode, name As String)

参数

initialState
Boolean

如果将命名事件作为此调用的结果创建时将初始状态设置为通过信号通知,则为 true;如果将其设置为不通过信号通知,则为 falsetrue to set the initial state to signaled if the named event is created as a result of this call; false to set it to nonsignaled.

mode
EventResetMode

其中一个 EventResetMode 值,它确定是自动还是手动重置事件。One of the EventResetMode values that determines whether the event resets automatically or manually.

name
String

系统范围的同步事件名称。The name of a system-wide synchronization event.

属性

异常

出现 Win32 错误。A Win32 error occurred.

命名事件存在且具有访问控制安全性,但用户不具有 FullControlThe named event exists and has access control security, but the user does not have FullControl.

无法创建命名事件,可能是因为其他类型的等待句柄具有相同名称。The named event cannot be created, perhaps because a wait handle of a different type has the same name.

name 超过 260 个字符。name is longer than 260 characters.

注解

如果name EventWaitHandlenull或空字符串,则创建一个本地。If name is null or an empty string, a local EventWaitHandle is created.

如果为name参数指定了名称的系统事件已存在,则忽略该initialState参数。If a system event with the name specified for the name parameter already exists, the initialState parameter is ignored.

重要

对已命名的系统事件使用此构造函数falseinitialState,请将指定为。When using this constructor for named system events, specify false for initialState. 此构造函数无法确定是否已创建已命名的系统事件,因此您无法对命名事件的状态进行任何假设。This constructor provides no way to determine whether a named system event was created, so you cannot make any assumptions about the state of the named event. 若要确定是否已创建命名事件,请使用EventWaitHandle(Boolean, EventResetMode, String, Boolean)构造函数EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity)或构造函数。To determine whether a named event was created, use the EventWaitHandle(Boolean, EventResetMode, String, Boolean) constructor or the EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity) constructor.

如果事件的初始状态为非终止,则等待事件的线程将会阻止。If the initial state of the event is nonsignaled, threads that wait on the event will block. 如果初始状态为 "已终止" 并且ManualResetmode指定了标志,则等待事件的线程不会阻塞。If the initial state is signaled, and the ManualReset flag is specified for mode, threads that wait on the event will not block. 如果初始状态为 "已终止" modeAutoReset并且为,则将立即释放等待事件的第一个线程,在此之后,事件将被重置,后续线程将被阻止。If the initial state is signaled, and mode is AutoReset, the first thread that waits on the event will be released immediately, after which the event will reset, and subsequent threads will block.

安全性

SecurityCriticalAttribute
需要对直接调用方的完全信任。Requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

另请参阅

EventWaitHandle(Boolean, EventResetMode, String, Boolean)

初始化 EventWaitHandle 类的新实例,指定如果将等待句柄作为此调用的结果而创建,最初是否通过信号通知此句柄;指定是否自动或手动重置系统同步事件的名称,以及一个布尔变量,在调用后其值指示是否创建了命名的系统事件。Initializes a new instance of the EventWaitHandle class, specifying whether the wait handle is initially signaled if created as a result of this call, whether it resets automatically or manually, the name of a system synchronization event, and a Boolean variable whose value after the call indicates whether the named system event was created.

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew);
[System.Security.SecurityCritical]
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew);
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode, name As String, ByRef createdNew As Boolean)

参数

initialState
Boolean

如果将命名事件作为此调用的结果创建时将初始状态设置为通过信号通知,则为 true;如果将其设置为不通过信号通知,则为 falsetrue to set the initial state to signaled if the named event is created as a result of this call; false to set it to nonsignaled.

mode
EventResetMode

其中一个 EventResetMode 值,它确定是自动还是手动重置事件。One of the EventResetMode values that determines whether the event resets automatically or manually.

name
String

系统范围的同步事件名称。The name of a system-wide synchronization event.

createdNew
Boolean

在此方法返回时,如果创建了本地事件(即,如果 nametrue 或空字符串)或指定的命名系统事件,则包含 null;如果指定的命名系统事件已存在,则为 falseWhen this method returns, contains true if a local event was created (that is, if name is null or an empty string) or if the specified named system event was created; false if the specified named system event already existed. 此参数未经初始化即被传递。This parameter is passed uninitialized.

属性

异常

出现 Win32 错误。A Win32 error occurred.

命名事件存在且具有访问控制安全性,但用户不具有 FullControlThe named event exists and has access control security, but the user does not have FullControl.

无法创建命名事件,可能是因为其他类型的等待句柄具有相同名称。The named event cannot be created, perhaps because a wait handle of a different type has the same name.

name 超过 260 个字符。name is longer than 260 characters.

注解

如果为name参数指定了名称的系统事件已存在,则忽略该initialState参数。If a system event with the name specified for the name parameter already exists, the initialState parameter is ignored. 调用此构造函数后,使用为ref参数指定的变量(ByRef Visual Basic 中的参数)createdNew中的值,以确定是否已存在或已创建已命名的系统事件。After calling this constructor, use the value in the variable specified for the ref parameter (ByRef parameter in Visual Basic)createdNew to determine whether the named system event already existed or was created.

如果事件的初始状态为非终止,则等待事件的线程将会阻止。If the initial state of the event is nonsignaled, threads that wait on the event will block. 如果初始状态为 "已终止" 并且ManualResetmode指定了标志,则等待事件的线程不会阻塞。If the initial state is signaled, and the ManualReset flag is specified for mode, threads that wait on the event will not block. 如果初始状态为 "已终止" modeAutoReset并且为,则将立即释放等待事件的第一个线程,在此之后,事件将被重置,后续线程将被阻止。If the initial state is signaled, and mode is AutoReset, the first thread that waits on the event will be released immediately, after which the event will reset, and subsequent threads will block.

安全性

SecurityCriticalAttribute
需要对直接调用方的完全信任。Requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

另请参阅

EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity)

初始化 EventWaitHandle 类的新实例,指定如果等待句柄作为此调用的结果而创建,最初是否通过信号通知此句柄;指定是否自动或手动重置系统同步事件的名称和布尔变量,其值在该调用后将指示是否创建了已命名系统事件,以及是否将访问控制安全性应用到命名事件(如果已创建该事件)。Initializes a new instance of the EventWaitHandle class, specifying whether the wait handle is initially signaled if created as a result of this call, whether it resets automatically or manually, the name of a system synchronization event, a Boolean variable whose value after the call indicates whether the named system event was created, and the access control security to be applied to the named event if it is created.

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew, System::Security::AccessControl::EventWaitHandleSecurity ^ eventSecurity);
[System.Security.SecurityCritical]
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew, System.Security.AccessControl.EventWaitHandleSecurity eventSecurity);
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool * System.Security.AccessControl.EventWaitHandleSecurity -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode, name As String, ByRef createdNew As Boolean, eventSecurity As EventWaitHandleSecurity)

参数

initialState
Boolean

如果将命名事件作为此调用的结果创建时将初始状态设置为通过信号通知,则为 true;如果将其设置为不通过信号通知,则为 falsetrue to set the initial state to signaled if the named event is created as a result of this call; false to set it to nonsignaled.

mode
EventResetMode

其中一个 EventResetMode 值,它确定是自动还是手动重置事件。One of the EventResetMode values that determines whether the event resets automatically or manually.

name
String

系统范围的同步事件名称。The name of a system-wide synchronization event.

createdNew
Boolean

在此方法返回时,如果创建了本地事件(即,如果 nametrue 或空字符串)或指定的命名系统事件,则包含 null;如果指定的命名系统事件已存在,则为 falseWhen this method returns, contains true if a local event was created (that is, if name is null or an empty string) or if the specified named system event was created; false if the specified named system event already existed. 此参数未经初始化即被传递。This parameter is passed uninitialized.

eventSecurity
EventWaitHandleSecurity

一个 EventWaitHandleSecurity 对象,该对象表示应用到命名系统事件的访问控制安全性。An EventWaitHandleSecurity object that represents the access control security to be applied to the named system event.

属性

异常

出现 Win32 错误。A Win32 error occurred.

命名事件存在且具有访问控制安全性,但用户不具有 FullControlThe named event exists and has access control security, but the user does not have FullControl.

无法创建命名事件,可能是因为其他类型的等待句柄具有相同名称。The named event cannot be created, perhaps because a wait handle of a different type has the same name.

name 超过 260 个字符。name is longer than 260 characters.

示例

下面的代码示例演示具有访问控制安全性的已命名系统事件的跨进程行为。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.

如果从两个命令窗口运行已编译的示例,第二个副本将在调用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). 捕获到异常,该示例使用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 

注解

使用此构造函数在创建已命名的系统事件时将其应用于该事件,从而防止其他代码控制该事件。Use this constructor to apply access control security to a named system event when it is created, preventing other code from taking control of the event.

此构造函数初始化EventWaitHandle表示系统事件的对象。This constructor initializes an EventWaitHandle object that represents a system event. 可以创建多个EventWaitHandle表示同一系统事件的对象。You can create multiple EventWaitHandle objects that represent the same system event.

如果系统事件不存在,则将使用指定的访问控制安全性来创建它。If the system event does not exist, it is created with the specified access control security. 如果该事件存在,则忽略指定的访问控制安全性。If the event exists, the specified access control security is ignored.

备注

调用方对新创建EventWaitHandle的对象拥有完全控制权, eventSecurity即使拒绝或无法向当前用户授予某些访问权限。The caller has full control over the newly created EventWaitHandle object even if eventSecurity denies or fails to grant some access rights to the current user. 但是,如果当前用户尝试使用构造函数EventWaitHandle OpenExisting或方法获取表示相同命名事件的另一个对象,则应用 Windows 访问控制安全性。However, if the current user attempts to get another EventWaitHandle object to represent the same named event, using either a constructor or the OpenExisting method, Windows access control security is applied.

如果为name参数指定了名称的系统事件已存在,则忽略该initialState参数。If a system event with the name specified for the name parameter already exists, the initialState parameter is ignored. 调用此构造函数后,使用为ref参数指定的变量(ByRef Visual Basic 中的参数) createdNew中的值,以确定是否已存在或已创建已命名的系统事件。After calling this constructor, use the value in the variable specified for the ref parameter (ByRef parameter in Visual Basic) createdNew to determine whether the named system event already existed or was created.

如果事件的初始状态为非终止,则等待事件的线程将会阻止。If the initial state of the event is nonsignaled, threads that wait on the event will block. 如果初始状态为 "已终止" 并且ManualResetmode指定了标志,则等待事件的线程不会阻塞。If the initial state is signaled, and the ManualReset flag is specified for mode, threads that wait on the event will not block. 如果初始状态为 "已终止" modeAutoReset并且为,则将立即释放等待事件的第一个线程,在此之后,事件将被重置,后续线程将被阻止。If the initial state is signaled, and mode is AutoReset, the first thread that waits on the event will be released immediately, after which the event will reset, and subsequent threads will block.

安全性

SecurityCriticalAttribute
需要对直接调用方的完全信任。Requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

另请参阅

适用于