EventWaitHandle Construtores
Definição
Inicializa uma nova instância da classe EventWaitHandle.Initializes a new instance of the EventWaitHandle class.
Sobrecargas
| EventWaitHandle(Boolean, EventResetMode) |
Inicializa uma nova instância da classe EventWaitHandle, especificando se o identificador de espera é sinalizado inicialmente e se ele redefine automática ou 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) |
Inicializa uma nova instância da classe EventWaitHandle, especificando se o identificador de espera é sinalizado inicialmente se for criado como resultado dessa chamada, se ele é redefinido manual ou automaticamente e o nome de um evento de sincronização do 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) |
Inicializa uma nova instância da classe EventWaitHandle, especificando se o identificador de espera é sinalizado inicialmente se for criado como resultado dessa chamada, se ele é redefinido manual ou automaticamente, o nome de um evento de sincronização do sistema e uma variável booliana cujo valor após a chamada indica se o evento de sistema nomeado foi criado.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) |
Inicializa uma nova instância da classe EventWaitHandle, especificando se o identificador de espera é sinalizado inicialmente se for criado como resultado dessa chamada, se ele é redefinido manual ou automaticamente, o nome de um evento de sincronização do sistema, uma variável booliana cujo valor após a chamada indica se o evento de sistema nomeado foi criado e a segurança de controle de acesso a ser aplicada ao evento nomeado se ele tiver sido criado.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)
Inicializa uma nova instância da classe EventWaitHandle, especificando se o identificador de espera é sinalizado inicialmente e se ele redefine automática ou 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)
Parâmetros
- initialState
- Boolean
true para definir o estado inicial como sinalizado; false para defini-lo como não sinalizado.true to set the initial state to signaled; false to set it to nonsignaled.
- mode
- EventResetMode
Um dos valores EventResetMode que determina se o evento redefine automática ou manualmente.One of the EventResetMode values that determines whether the event resets automatically or manually.
Exceções
O valor de enumeração mode estava fora do intervalo legal.The mode enum value was out of legal range.
Exemplos
O exemplo de código a seguir usa a SignalAndWait(WaitHandle, WaitHandle) sobrecarga do método para permitir que o thread principal sinalize um thread bloqueado e aguarde até que o thread conclua uma tarefa.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.
O exemplo inicia cinco threads e permite que eles sejam bloqueados em um EventWaitHandle criado com o sinalizador e, EventResetMode.AutoReset em seguida, libera um thread cada vez que o usuário pressiona Enter Key.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. Em seguida, o exemplo enfileira outros cinco threads e os libera usando um EventWaitHandle criado com o EventResetMode.ManualReset sinalizador.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
Comentários
Se o estado inicial do evento não estiver sinalizado, os threads que aguardam o evento serão bloqueados.If the initial state of the event is nonsignaled, threads that wait on the event will block. Se o estado inicial for sinalizado e o ManualReset sinalizador for especificado para mode , os threads que aguardam o evento não serão bloqueados.If the initial state is signaled, and the ManualReset flag is specified for mode, threads that wait on the event will not block. Se o estado inicial for sinalizado e mode for AutoReset , o primeiro thread que aguarda o evento será liberado imediatamente, após o qual o evento será redefinido e os threads subsequentes serão bloqueados.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.
Aplica-se a
EventWaitHandle(Boolean, EventResetMode, String)
Inicializa uma nova instância da classe EventWaitHandle, especificando se o identificador de espera é sinalizado inicialmente se for criado como resultado dessa chamada, se ele é redefinido manual ou automaticamente e o nome de um evento de sincronização do 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);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string? name);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name);
[<System.Security.SecurityCritical>]
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string -> System.Threading.EventWaitHandle
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode, name As String)
Parâmetros
- initialState
- Boolean
true para definir o estado inicial como sinalizado se o evento nomeado for criado como resultado dessa chamada, false para defini-lo como não sinalizado.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
Um dos valores EventResetMode que determina se o evento redefine automática ou manualmente.One of the EventResetMode values that determines whether the event resets automatically or manually.
- name
- String
O nome, se o objeto de sincronização for ser compartilhado com outros processos; caso contrário, null ou uma cadeia de caracteres vazia.The name, if the synchronization object is to be shared with other processes; otherwise, null or an empty string. O nome diferencia maiúsculas de minúsculas.The name is case-sensitive.
- Atributos
Exceções
name é inválido.name is invalid. Isso pode ser por vários motivos, incluindo algumas restrições impostas pelo sistema operacional, como um prefixo desconhecido ou caracteres inválidos.This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. Observe que o nome e os prefixos comuns "Global" e "Local" diferenciam maiúsculas de minúsculas.Note that the name and common prefixes "Global" and "Local" are case-sensitive.
- ou --or-
Ocorreu outro erro.There was some other error. A propriedade HResult pode fornecer mais informações.The HResult property may provide more information.
Somente Windows: name especificou um namespace desconhecido.Windows only: name specified an unknown namespace. Confira mais informações em Nomes do objeto.See Object Names for more information.
O name é muito longo.The name is too long. As restrições de comprimento podem depender do sistema operacional ou da configuração.Length restrictions may depend on the operating system or configuration.
O evento nomeado existe e tem segurança de controle de acesso, mas o usuário não tem FullControl.The named event exists and has access control security, but the user does not have FullControl.
Não é possível criar um objeto de sincronização com o name fornecido.A synchronization object with the provided name cannot be created. Um objeto de sincronização de um tipo diferente pode ter o mesmo nome.A synchronization object of a different type might have the same name.
O valor de enumeração mode estava fora do intervalo legal.The mode enum value was out of legal range.
- ou --or-
Somente .NET Framework: name é maior que MAX_PATH (260 caracteres)..NET Framework only: name is longer than MAX_PATH (260 characters).
Comentários
O name pode ser prefixado com Global\ or Local\ para especificar um namespace.The name may be prefixed with Global\ or Local\ to specify a namespace. Quando o Global namespace é especificado, o objeto de sincronização pode ser compartilhado com qualquer processo no sistema.When the Global namespace is specified, the synchronization object may be shared with any processes on the system. Quando o Local namespace é especificado, que também é o padrão quando nenhum namespace é especificado, o objeto de sincronização pode ser compartilhado com processos na mesma sessão.When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. No Windows, uma sessão é uma sessão de logon e os serviços normalmente são executados em uma sessão não interativa diferente.On Windows, a session is a login session, and services typically run in a different non-interactive session. Em sistemas operacionais semelhantes ao Unix, cada shell tem sua própria sessão.On Unix-like operating systems, each shell has its own session. Os objetos de sincronização de sessão local podem ser apropriados para sincronizar entre processos com uma relação pai/filho em que todos eles são executados na mesma sessão.Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. Para obter mais informações sobre nomes de objetos Synchornization no Windows, consulte nomes de objetos.For more information about synchornization object names on Windows, see Object Names.
Se um name for fornecido e um objeto de sincronização do tipo solicitado já existir no namespace, o objeto de sincronização existente será aberto.If a name is provided and a synchronization object of the requested type already exists in the namespace, the existing synchronization object is opened. Se um objeto de sincronização de um tipo diferente já existir no namespace, um WaitHandleCannotBeOpenedException será gerado.If a synchronization object of a different type already exists in the namespace, a WaitHandleCannotBeOpenedException is thrown. Caso contrário, um novo objeto de sincronização será criado.Otherwise, a new synchronization object is created.
Se um evento do sistema com o nome especificado para o name parâmetro já existir, o initialState parâmetro será ignorado.If a system event with the name specified for the name parameter already exists, the initialState parameter is ignored.
Importante
Ao usar esse construtor para eventos de sistema nomeados, especifique false for initialState .When using this constructor for named system events, specify false for initialState. Esse construtor não fornece nenhuma maneira de determinar se um evento de sistema nomeado foi criado, portanto, você não pode fazer suposições sobre o estado do evento nomeado.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. Para determinar se um evento nomeado foi criado, use o EventWaitHandle(Boolean, EventResetMode, String, Boolean) Construtor ou o EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity) Construtor.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 o estado inicial do evento não estiver sinalizado, os threads que aguardam o evento serão bloqueados.If the initial state of the event is nonsignaled, threads that wait on the event will block. Se o estado inicial for sinalizado e o ManualReset sinalizador for especificado para mode , os threads que aguardam o evento não serão bloqueados.If the initial state is signaled, and the ManualReset flag is specified for mode, threads that wait on the event will not block. Se o estado inicial for sinalizado e mode for AutoReset , o primeiro thread que aguarda o evento será liberado imediatamente, após o qual o evento será redefinido e os threads subsequentes serão bloqueados.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.
Aplica-se a
EventWaitHandle(Boolean, EventResetMode, String, Boolean)
Inicializa uma nova instância da classe EventWaitHandle, especificando se o identificador de espera é sinalizado inicialmente se for criado como resultado dessa chamada, se ele é redefinido manual ou automaticamente, o nome de um evento de sincronização do sistema e uma variável booliana cujo valor após a chamada indica se o evento de sistema nomeado foi criado.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);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string? name, out bool? createdNew);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew);
[<System.Security.SecurityCritical>]
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool -> System.Threading.EventWaitHandle
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)
Parâmetros
- initialState
- Boolean
true para definir o estado inicial como sinalizado se o evento nomeado for criado como resultado dessa chamada, false para defini-lo como não sinalizado.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
Um dos valores EventResetMode que determina se o evento redefine automática ou manualmente.One of the EventResetMode values that determines whether the event resets automatically or manually.
- name
- String
O nome, se o objeto de sincronização for ser compartilhado com outros processos; caso contrário, null ou uma cadeia de caracteres vazia.The name, if the synchronization object is to be shared with other processes; otherwise, null or an empty string. O nome diferencia maiúsculas de minúsculas.The name is case-sensitive.
- createdNew
- Boolean
Quando esse método for retornado, conterá true se um evento local tiver sido criado (ou seja, se name for null ou uma cadeia de caracteres vazia) ou se o evento de sistema nomeado especificado tiver sido criado; false se o evento de sistema nomeado especificado já existia.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. Este parâmetro é passado não inicializado.This parameter is passed uninitialized.
- Atributos
Exceções
name é inválido.name is invalid. Isso pode ser por vários motivos, incluindo algumas restrições impostas pelo sistema operacional, como um prefixo desconhecido ou caracteres inválidos.This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. Observe que o nome e os prefixos comuns "Global" e "Local" diferenciam maiúsculas de minúsculas.Note that the name and common prefixes "Global" and "Local" are case-sensitive.
- ou --or-
Ocorreu outro erro.There was some other error. A propriedade HResult pode fornecer mais informações.The HResult property may provide more information.
Somente Windows: name especificou um namespace desconhecido.Windows only: name specified an unknown namespace. Confira mais informações em Nomes do objeto.See Object Names for more information.
O name é muito longo.The name is too long. As restrições de comprimento podem depender do sistema operacional ou da configuração.Length restrictions may depend on the operating system or configuration.
O evento nomeado existe e tem segurança de controle de acesso, mas o usuário não tem FullControl.The named event exists and has access control security, but the user does not have FullControl.
Não é possível criar um objeto de sincronização com o name fornecido.A synchronization object with the provided name cannot be created. Um objeto de sincronização de um tipo diferente pode ter o mesmo nome.A synchronization object of a different type might have the same name.
O valor de enumeração mode estava fora do intervalo legal.The mode enum value was out of legal range.
- ou --or-
Somente .NET Framework: name é maior que MAX_PATH (260 caracteres)..NET Framework only: name is longer than MAX_PATH (260 characters).
Comentários
O name pode ser prefixado com Global\ or Local\ para especificar um namespace.The name may be prefixed with Global\ or Local\ to specify a namespace. Quando o Global namespace é especificado, o objeto de sincronização pode ser compartilhado com qualquer processo no sistema.When the Global namespace is specified, the synchronization object may be shared with any processes on the system. Quando o Local namespace é especificado, que também é o padrão quando nenhum namespace é especificado, o objeto de sincronização pode ser compartilhado com processos na mesma sessão.When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. No Windows, uma sessão é uma sessão de logon e os serviços normalmente são executados em uma sessão não interativa diferente.On Windows, a session is a login session, and services typically run in a different non-interactive session. Em sistemas operacionais semelhantes ao Unix, cada shell tem sua própria sessão.On Unix-like operating systems, each shell has its own session. Os objetos de sincronização de sessão local podem ser apropriados para sincronizar entre processos com uma relação pai/filho em que todos eles são executados na mesma sessão.Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. Para obter mais informações sobre nomes de objetos Synchornization no Windows, consulte nomes de objetos.For more information about synchornization object names on Windows, see Object Names.
Se um name for fornecido e um objeto de sincronização do tipo solicitado já existir no namespace, o objeto de sincronização existente será aberto.If a name is provided and a synchronization object of the requested type already exists in the namespace, the existing synchronization object is opened. Se um objeto de sincronização de um tipo diferente já existir no namespace, um WaitHandleCannotBeOpenedException será gerado.If a synchronization object of a different type already exists in the namespace, a WaitHandleCannotBeOpenedException is thrown. Caso contrário, um novo objeto de sincronização será criado.Otherwise, a new synchronization object is created.
Se um evento do sistema com o nome especificado para o name parâmetro já existir, o initialState parâmetro será ignorado.If a system event with the name specified for the name parameter already exists, the initialState parameter is ignored. Depois de chamar esse construtor, use o valor na variável especificada para o ref parâmetro ( ByRef parâmetro em Visual Basic) createdNew para determinar se o evento de sistema nomeado já existia ou se foi criado.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 o estado inicial do evento não estiver sinalizado, os threads que aguardam o evento serão bloqueados.If the initial state of the event is nonsignaled, threads that wait on the event will block. Se o estado inicial for sinalizado e o ManualReset sinalizador for especificado para mode , os threads que aguardam o evento não serão bloqueados.If the initial state is signaled, and the ManualReset flag is specified for mode, threads that wait on the event will not block. Se o estado inicial for sinalizado e mode for AutoReset , o primeiro thread que aguarda o evento será liberado imediatamente, após o qual o evento será redefinido e os threads subsequentes serão bloqueados.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.
Aplica-se a
EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity)
Inicializa uma nova instância da classe EventWaitHandle, especificando se o identificador de espera é sinalizado inicialmente se for criado como resultado dessa chamada, se ele é redefinido manual ou automaticamente, o nome de um evento de sincronização do sistema, uma variável booliana cujo valor após a chamada indica se o evento de sistema nomeado foi criado e a segurança de controle de acesso a ser aplicada ao evento nomeado se ele tiver sido criado.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);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, 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
[<System.Security.SecurityCritical>]
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)
Parâmetros
- initialState
- Boolean
true para definir o estado inicial como sinalizado se o evento nomeado for criado como resultado dessa chamada, false para defini-lo como não sinalizado.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
Um dos valores EventResetMode que determina se o evento redefine automática ou manualmente.One of the EventResetMode values that determines whether the event resets automatically or manually.
- name
- String
O nome, se o objeto de sincronização for ser compartilhado com outros processos; caso contrário, null ou uma cadeia de caracteres vazia.The name, if the synchronization object is to be shared with other processes; otherwise, null or an empty string. O nome diferencia maiúsculas de minúsculas.The name is case-sensitive.
- createdNew
- Boolean
Quando esse método for retornado, conterá true se um evento local tiver sido criado (ou seja, se name for null ou uma cadeia de caracteres vazia) ou se o evento de sistema nomeado especificado tiver sido criado; false se o evento de sistema nomeado especificado já existia.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. Este parâmetro é passado não inicializado.This parameter is passed uninitialized.
- eventSecurity
- EventWaitHandleSecurity
Um objeto EventWaitHandleSecurity que representa a segurança de controle de acesso a ser aplicada ao evento de sistema nomeado.An EventWaitHandleSecurity object that represents the access control security to be applied to the named system event.
- Atributos
Exceções
name é inválido.name is invalid. Isso pode ser por vários motivos, incluindo algumas restrições impostas pelo sistema operacional, como um prefixo desconhecido ou caracteres inválidos.This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. Observe que o nome e os prefixos comuns "Global" e "Local" diferenciam maiúsculas de minúsculas.Note that the name and common prefixes "Global" and "Local" are case-sensitive.
- ou --or-
Ocorreu outro erro.There was some other error. A propriedade HResult pode fornecer mais informações.The HResult property may provide more information.
Somente Windows: name especificou um namespace desconhecido.Windows only: name specified an unknown namespace. Confira mais informações em Nomes do objeto.See Object Names for more information.
O name é muito longo.The name is too long. As restrições de comprimento podem depender do sistema operacional ou da configuração.Length restrictions may depend on the operating system or configuration.
O evento nomeado existe e tem segurança de controle de acesso, mas o usuário não tem FullControl.The named event exists and has access control security, but the user does not have FullControl.
Não é possível criar um objeto de sincronização com o name fornecido.A synchronization object with the provided name cannot be created. Um objeto de sincronização de um tipo diferente pode ter o mesmo nome.A synchronization object of a different type might have the same name.
O valor de enumeração mode estava fora do intervalo legal.The mode enum value was out of legal range.
- ou --or-
Somente .NET Framework: name é maior que MAX_PATH (260 caracteres)..NET Framework only: name is longer than MAX_PATH (260 characters).
Exemplos
O exemplo de código a seguir demonstra o comportamento de processo cruzado de um evento do sistema nomeado com segurança de controle de acesso.The following code example demonstrates the cross-process behavior of a named system event with access control security. O exemplo usa a OpenExisting(String) sobrecarga do método para testar a existência de um evento nomeado.The example uses the OpenExisting(String) method overload to test for the existence of a named event.
Se o evento não existir, ele será criado com a propriedade inicial e a segurança de controle de acesso que nega ao usuário atual o direito de usar o evento, mas concede o direito de ler e alterar permissões no 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 você executar o exemplo compilado de duas janelas de comando, a segunda cópia gerará uma exceção de violação de acesso na chamada para 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). A exceção é capturada e o exemplo usa a OpenExisting(String, EventWaitHandleRights) sobrecarga do método para aguardar o evento com os direitos necessários para ler e alterar as permissões.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.
Depois que as permissões forem alteradas, o evento será aberto com os direitos necessários para aguardar e signalá-lo.After the permissions are changed, the event is opened with the rights required to wait on it and signal it. Se você executar o exemplo compilado de uma terceira janela de comando, o exemplo será executado usando as novas permissões.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
Comentários
Use este construtor para aplicar a segurança de controle de acesso a um evento de sistema nomeado quando ele é criado, impedindo que outro código controle o 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.
Esse construtor inicializa um EventWaitHandle objeto que representa um evento do sistema.This constructor initializes an EventWaitHandle object that represents a system event. Você pode criar vários EventWaitHandle objetos que representam o mesmo evento do sistema.You can create multiple EventWaitHandle objects that represent the same system event.
Se o evento do sistema não existir, ele será criado com a segurança de controle de acesso especificada.If the system event does not exist, it is created with the specified access control security. Se o evento existir, a segurança de controle de acesso especificada será ignorada.If the event exists, the specified access control security is ignored.
Observação
O chamador tem controle total sobre o objeto recém-criado EventWaitHandle , mesmo que eventSecurity negue ou não conceda alguns direitos de acesso ao usuário atual.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. No entanto, se o usuário atual tentar obter outro EventWaitHandle objeto para representar o mesmo evento nomeado, usando um construtor ou o OpenExisting método, a segurança do controle de acesso do Windows será aplicada.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.
O name pode ser prefixado com Global\ or Local\ para especificar um namespace.The name may be prefixed with Global\ or Local\ to specify a namespace. Quando o Global namespace é especificado, o objeto de sincronização pode ser compartilhado com qualquer processo no sistema.When the Global namespace is specified, the synchronization object may be shared with any processes on the system. Quando o Local namespace é especificado, que também é o padrão quando nenhum namespace é especificado, o objeto de sincronização pode ser compartilhado com processos na mesma sessão.When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. No Windows, uma sessão é uma sessão de logon e os serviços normalmente são executados em uma sessão não interativa diferente.On Windows, a session is a login session, and services typically run in a different non-interactive session. Em sistemas operacionais semelhantes ao Unix, cada shell tem sua própria sessão.On Unix-like operating systems, each shell has its own session. Os objetos de sincronização de sessão local podem ser apropriados para sincronizar entre processos com uma relação pai/filho em que todos eles são executados na mesma sessão.Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. Para obter mais informações sobre nomes de objetos Synchornization no Windows, consulte nomes de objetos.For more information about synchornization object names on Windows, see Object Names.
Se um name for fornecido e um objeto de sincronização do tipo solicitado já existir no namespace, o objeto de sincronização existente será aberto.If a name is provided and a synchronization object of the requested type already exists in the namespace, the existing synchronization object is opened. Se um objeto de sincronização de um tipo diferente já existir no namespace, um WaitHandleCannotBeOpenedException será gerado.If a synchronization object of a different type already exists in the namespace, a WaitHandleCannotBeOpenedException is thrown. Caso contrário, um novo objeto de sincronização será criado.Otherwise, a new synchronization object is created.
Se um evento do sistema com o nome especificado para o name parâmetro já existir, o initialState parâmetro será ignorado.If a system event with the name specified for the name parameter already exists, the initialState parameter is ignored. Depois de chamar esse construtor, use o valor na variável especificada para o ref parâmetro ( ByRef parâmetro em Visual Basic) createdNew para determinar se o evento de sistema nomeado já existia ou se foi criado.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 o estado inicial do evento não estiver sinalizado, os threads que aguardam o evento serão bloqueados.If the initial state of the event is nonsignaled, threads that wait on the event will block. Se o estado inicial for sinalizado e o ManualReset sinalizador for especificado para mode , os threads que aguardam o evento não serão bloqueados.If the initial state is signaled, and the ManualReset flag is specified for mode, threads that wait on the event will not block. Se o estado inicial for sinalizado e mode for AutoReset , o primeiro thread que aguarda o evento será liberado imediatamente, após o qual o evento será redefinido e os threads subsequentes serão bloqueados.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.