EventWaitHandle Costruttori

Definizione

Inizializza una nuova istanza della classe EventWaitHandle.Initializes a new instance of the EventWaitHandle class.

Overload

EventWaitHandle(Boolean, EventResetMode)

Inizializza una nuova istanza della classe EventWaitHandle, specificando se l'handle di attesa è inizialmente segnalato e se la reimpostazione viene eseguita automaticamente o manualmente.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)

Inizializza una nuova istanza della classe EventWaitHandle, specificando se l'handle di attesa è inizialmente segnalato se creato a seguito di questa chiamata e se la reimpostazione viene eseguita automaticamente o manualmente e indicando il nome di un evento di sincronizzazione di sistema.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)

Inizializza una nuova istanza della classe EventWaitHandle, che specifica se l'handle di attesa viene inizialmente segnalato se creato in seguito alla chiamata, se viene reimpostato automaticamente o manualmente, nonché il nome di un evento di sincronizzazione di sistema e una variabile Boolean il cui valore dopo la chiamata indica se è stato creato l'evento di sistema denominato.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)

Inizializza una nuova istanza della classe EventWaitHandle, che specifica se l'handle di attesa viene inizialmente segnalato se creato in seguito alla chiamata, se viene reimpostato automaticamente o manualmente, nonché il nome di un evento di sincronizzazione di sistema, una variabile Boolean il cui valore dopo la chiamata indica se è stato creato l'evento di sistema denominato e la sicurezza del controllo di accesso da applicare all'evento denominato, se è stato creato.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)

Inizializza una nuova istanza della classe EventWaitHandle, specificando se l'handle di attesa è inizialmente segnalato e se la reimpostazione viene eseguita automaticamente o manualmente.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)

Parametri

initialState
Boolean

true per impostare lo stato iniziale su segnalato; false per impostarlo su non segnalato.true to set the initial state to signaled; false to set it to nonsignaled.

mode
EventResetMode

Ottiene uno dei valori di EventResetMode che determina se l'evento viene reimpostato manualmente o automaticamente.One of the EventResetMode values that determines whether the event resets automatically or manually.

Esempi

Nell'esempio di codice seguente viene SignalAndWait(WaitHandle, WaitHandle) usato l'overload del metodo per consentire al thread principale di segnalare un thread bloccato e quindi attendere il completamento di un'attività da parte del thread.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.

L'esempio avvia cinque thread e li consente di bloccarsi su EventWaitHandle un oggetto creato EventResetMode.AutoReset con il flag, quindi rilascia un thread ogni volta che l'utente preme INVIO.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. L'esempio accoda quindi altri cinque thread e li rilascia tutti usando un oggetto EventWaitHandle creato con il EventResetMode.ManualReset flag.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

Commenti

Se lo stato iniziale dell'evento non è segnalato, i thread che attendono l'evento si bloccherà.If the initial state of the event is nonsignaled, threads that wait on the event will block. Se lo stato iniziale viene segnalato e il ManualReset flag viene specificato per mode, i thread che attendono l'evento non vengono bloccati.If the initial state is signaled, and the ManualReset flag is specified for mode, threads that wait on the event will not block. Se lo stato iniziale viene segnalato e mode è AutoReset, il primo thread che attende l'evento verrà rilasciato immediatamente, dopo il quale l'evento verrà reimpostato e i thread successivi verranno bloccati.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.

Vedi anche

EventWaitHandle(Boolean, EventResetMode, String)

Inizializza una nuova istanza della classe EventWaitHandle, specificando se l'handle di attesa è inizialmente segnalato se creato a seguito di questa chiamata e se la reimpostazione viene eseguita automaticamente o manualmente e indicando il nome di un evento di sincronizzazione di sistema.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)

Parametri

initialState
Boolean

true per impostare lo stato iniziale su segnalato se l'evento denominato viene creato come risultato della chiamata; false per impostarlo su non segnalato.true 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

Ottiene uno dei valori di EventResetMode che determina se l'evento viene reimpostato manualmente o automaticamente.One of the EventResetMode values that determines whether the event resets automatically or manually.

name
String

Nome di un evento di sincronizzazione a livello di sistema.The name of a system-wide synchronization event.

Attributi

Eccezioni

Errore Win32.A Win32 error occurred.

L'evento denominato esiste e include sicurezza del controllo di accesso, ma l'utente non ha FullControl.The named event exists and has access control security, but the user does not have FullControl.

L'evento denominato non può essere creato, forse perché ha lo stesso nome di un handle di attesa di tipo diverso.The named event cannot be created, perhaps because a wait handle of a different type has the same name.

La lunghezza di name supera i 260 caratteri.name is longer than 260 characters.

Commenti

Se name EventWaitHandle è null o una stringa vuota, viene creato un oggetto locale.If name is null or an empty string, a local EventWaitHandle is created.

Se esiste già un evento di sistema con il nome name specificato per il parametro, initialState il parametro viene ignorato.If a system event with the name specified for the name parameter already exists, the initialState parameter is ignored.

Importante

Quando si utilizza questo costruttore per gli eventi di sistema false denominati, specificare per. initialStateWhen using this constructor for named system events, specify false for initialState. Questo costruttore non fornisce alcun modo per determinare se è stato creato un evento di sistema denominato, pertanto non è possibile creare presupposti sullo stato dell'evento denominato.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. Per determinare se è stato creato un evento denominato, utilizzare EventWaitHandle(Boolean, EventResetMode, String, Boolean) il costruttore o EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity) il costruttore.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.

Se lo stato iniziale dell'evento non è segnalato, i thread che attendono l'evento si bloccherà.If the initial state of the event is nonsignaled, threads that wait on the event will block. Se lo stato iniziale viene segnalato e il ManualReset flag viene specificato per mode, i thread che attendono l'evento non vengono bloccati.If the initial state is signaled, and the ManualReset flag is specified for mode, threads that wait on the event will not block. Se lo stato iniziale viene segnalato e mode è AutoReset, il primo thread che attende l'evento verrà rilasciato immediatamente, dopo il quale l'evento verrà reimpostato e i thread successivi verranno bloccati.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.

Sicurezza

SecurityCriticalAttribute
richiede l'attendibilità totale per il chiamante immediato.Requires full trust for the immediate caller. Questo membro non può essere utilizzato da codice parzialmente attendibile o trasparente.This member cannot be used by partially trusted or transparent code.

Vedi anche

EventWaitHandle(Boolean, EventResetMode, String, Boolean)

Inizializza una nuova istanza della classe EventWaitHandle, che specifica se l'handle di attesa viene inizialmente segnalato se creato in seguito alla chiamata, se viene reimpostato automaticamente o manualmente, nonché il nome di un evento di sincronizzazione di sistema e una variabile Boolean il cui valore dopo la chiamata indica se è stato creato l'evento di sistema denominato.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)

Parametri

initialState
Boolean

true per impostare lo stato iniziale su segnalato se l'evento denominato viene creato come risultato della chiamata; false per impostarlo su non segnalato.true 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

Ottiene uno dei valori di EventResetMode che determina se l'evento viene reimpostato manualmente o automaticamente.One of the EventResetMode values that determines whether the event resets automatically or manually.

name
String

Nome di un evento di sincronizzazione a livello di sistema.The name of a system-wide synchronization event.

createdNew
Boolean

Quando questo metodo viene restituito, contiene true se è stato creato un evento locale (ovvero, se il valore di name è null o una stringa vuota) oppure se è stato creato l'evento di sistema denominato specificato; false se l'evento di sistema denominato specificato è già esistente.When 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. Questo parametro viene passato non inizializzato.This parameter is passed uninitialized.

Attributi

Eccezioni

Errore Win32.A Win32 error occurred.

L'evento denominato esiste e include sicurezza del controllo di accesso, ma l'utente non ha FullControl.The named event exists and has access control security, but the user does not have FullControl.

L'evento denominato non può essere creato, forse perché ha lo stesso nome di un handle di attesa di tipo diverso.The named event cannot be created, perhaps because a wait handle of a different type has the same name.

La lunghezza di name supera i 260 caratteri.name is longer than 260 characters.

Commenti

Se esiste già un evento di sistema con il nome name specificato per il parametro, initialState il parametro viene ignorato.If a system event with the name specified for the name parameter already exists, the initialState parameter is ignored. Dopo la chiamata a questo costruttore, utilizzare il valore nella variabile specificata per ref il parametroByRef (parametro in Visual BasiccreatedNew ) per determinare se l'evento di sistema denominato esiste già o è stato creato.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.

Se lo stato iniziale dell'evento non è segnalato, i thread che attendono l'evento si bloccherà.If the initial state of the event is nonsignaled, threads that wait on the event will block. Se lo stato iniziale viene segnalato e il ManualReset flag viene specificato per mode, i thread che attendono l'evento non vengono bloccati.If the initial state is signaled, and the ManualReset flag is specified for mode, threads that wait on the event will not block. Se lo stato iniziale viene segnalato e mode è AutoReset, il primo thread che attende l'evento verrà rilasciato immediatamente, dopo il quale l'evento verrà reimpostato e i thread successivi verranno bloccati.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.

Sicurezza

SecurityCriticalAttribute
richiede l'attendibilità totale per il chiamante immediato.Requires full trust for the immediate caller. Questo membro non può essere utilizzato da codice parzialmente attendibile o trasparente.This member cannot be used by partially trusted or transparent code.

Vedi anche

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

Inizializza una nuova istanza della classe EventWaitHandle, che specifica se l'handle di attesa viene inizialmente segnalato se creato in seguito alla chiamata, se viene reimpostato automaticamente o manualmente, nonché il nome di un evento di sincronizzazione di sistema, una variabile Boolean il cui valore dopo la chiamata indica se è stato creato l'evento di sistema denominato e la sicurezza del controllo di accesso da applicare all'evento denominato, se è stato creato.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)

Parametri

initialState
Boolean

true per impostare lo stato iniziale su segnalato se l'evento denominato viene creato come risultato della chiamata; false per impostarlo su non segnalato.true 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

Ottiene uno dei valori di EventResetMode che determina se l'evento viene reimpostato manualmente o automaticamente.One of the EventResetMode values that determines whether the event resets automatically or manually.

name
String

Nome di un evento di sincronizzazione a livello di sistema.The name of a system-wide synchronization event.

createdNew
Boolean

Quando questo metodo viene restituito, contiene true se è stato creato un evento locale (ovvero, se il valore di name è null o una stringa vuota) oppure se è stato creato l'evento di sistema denominato specificato; false se l'evento di sistema denominato specificato è già esistente.When 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. Questo parametro viene passato non inizializzato.This parameter is passed uninitialized.

eventSecurity
EventWaitHandleSecurity

Oggetto EventWaitHandleSecurity che rappresenta la sicurezza del controllo di accesso da applicare all'evento di sistema denominato.An EventWaitHandleSecurity object that represents the access control security to be applied to the named system event.

Attributi

Eccezioni

Errore Win32.A Win32 error occurred.

L'evento denominato esiste e include sicurezza del controllo di accesso, ma l'utente non ha FullControl.The named event exists and has access control security, but the user does not have FullControl.

L'evento denominato non può essere creato, forse perché ha lo stesso nome di un handle di attesa di tipo diverso.The named event cannot be created, perhaps because a wait handle of a different type has the same name.

La lunghezza di name supera i 260 caratteri.name is longer than 260 characters.

Esempi

Nell'esempio di codice riportato di seguito viene illustrato il comportamento tra processi di un evento di sistema denominato con sicurezza del controllo di accesso.The following code example demonstrates the cross-process behavior of a named system event with access control security. Nell'esempio viene utilizzato OpenExisting(String) l'overload del metodo per verificare l'esistenza di un evento denominato.The example uses the OpenExisting(String) method overload to test for the existence of a named event.

Se l'evento non esiste, viene creato con proprietà iniziale e sicurezza del controllo di accesso che nega all'utente corrente il diritto di utilizzare l'evento, ma concede il diritto di leggere e modificare le autorizzazioni per l'evento.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.

Se si esegue l'esempio compilato da due finestre di comando, la seconda copia genererà un'eccezione di violazione di accesso nella OpenExisting(String)chiamata a.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). L'eccezione viene rilevata e nell'esempio viene OpenExisting(String, EventWaitHandleRights) utilizzato l'overload del metodo per attendere l'evento con i diritti necessari per leggere e modificare le autorizzazioni.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.

Una volta modificate le autorizzazioni, l'evento viene aperto con i diritti necessari per attenderlo e segnalarlo.After the permissions are changed, the event is opened with the rights required to wait on it and signal it. Se si esegue l'esempio compilato da una terza finestra di comando, l'esempio viene eseguito utilizzando le nuove autorizzazioni.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 

Commenti

Utilizzare questo costruttore per applicare la sicurezza del controllo di accesso a un evento di sistema denominato quando viene creato, impedendo ad altro codice di assumere il controllo dell'evento.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.

Questo costruttore inizializza un EventWaitHandle oggetto che rappresenta un evento di sistema.This constructor initializes an EventWaitHandle object that represents a system event. È possibile creare più EventWaitHandle oggetti che rappresentano lo stesso evento di sistema.You can create multiple EventWaitHandle objects that represent the same system event.

Se l'evento di sistema non esiste, viene creato con la sicurezza del controllo di accesso specificata.If the system event does not exist, it is created with the specified access control security. Se l'evento esiste, la sicurezza del controllo di accesso specificata viene ignorata.If the event exists, the specified access control security is ignored.

Nota

Il chiamante ha il controllo completo sull'oggetto appena EventWaitHandle creato anche se eventSecurity nega o non riesce a concedere alcuni diritti di accesso all'utente corrente.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. Tuttavia, se l'utente corrente tenta di ottenere un EventWaitHandle altro oggetto per rappresentare lo stesso evento denominato, usando un costruttore o il OpenExisting metodo, viene applicata la sicurezza del controllo di accesso di 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.

Se esiste già un evento di sistema con il nome name specificato per il parametro, initialState il parametro viene ignorato.If a system event with the name specified for the name parameter already exists, the initialState parameter is ignored. Dopo la chiamata a questo costruttore, utilizzare il valore nella variabile specificata per ref il parametroByRef (parametro in Visual Basic createdNew ) per determinare se l'evento di sistema denominato esiste già o è stato creato.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.

Se lo stato iniziale dell'evento non è segnalato, i thread che attendono l'evento si bloccherà.If the initial state of the event is nonsignaled, threads that wait on the event will block. Se lo stato iniziale viene segnalato e il ManualReset flag viene specificato per mode, i thread che attendono l'evento non vengono bloccati.If the initial state is signaled, and the ManualReset flag is specified for mode, threads that wait on the event will not block. Se lo stato iniziale viene segnalato e mode è AutoReset, il primo thread che attende l'evento verrà rilasciato immediatamente, dopo il quale l'evento verrà reimpostato e i thread successivi verranno bloccati.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.

Sicurezza

SecurityCriticalAttribute
richiede l'attendibilità totale per il chiamante immediato.Requires full trust for the immediate caller. Questo membro non può essere utilizzato da codice parzialmente attendibile o trasparente.This member cannot be used by partially trusted or transparent code.

Vedi anche

Si applica a