WaitHandle.SignalAndWait WaitHandle.SignalAndWait WaitHandle.SignalAndWait WaitHandle.SignalAndWait Method

Definición

Señala un WaitHandle y espera en otro.Signals one WaitHandle and waits on another.

Sobrecargas

SignalAndWait(WaitHandle, WaitHandle) SignalAndWait(WaitHandle, WaitHandle) SignalAndWait(WaitHandle, WaitHandle) SignalAndWait(WaitHandle, WaitHandle)

Señala un WaitHandle y espera en otro.Signals one WaitHandle and waits on another.

SignalAndWait(WaitHandle, WaitHandle, Int32, Boolean) SignalAndWait(WaitHandle, WaitHandle, Int32, Boolean) SignalAndWait(WaitHandle, WaitHandle, Int32, Boolean) SignalAndWait(WaitHandle, WaitHandle, Int32, Boolean)

Señala un WaitHandle y espera en otro, para lo que determina un intervalo de tiempo de espera como entero con signo de 32 bits y especifica si se sale del dominio de sincronización para el contexto antes de entrar en la espera.Signals one WaitHandle and waits on another, specifying a time-out interval as a 32-bit signed integer and specifying whether to exit the synchronization domain for the context before entering the wait.

SignalAndWait(WaitHandle, WaitHandle, TimeSpan, Boolean) SignalAndWait(WaitHandle, WaitHandle, TimeSpan, Boolean) SignalAndWait(WaitHandle, WaitHandle, TimeSpan, Boolean) SignalAndWait(WaitHandle, WaitHandle, TimeSpan, Boolean)

Señala un WaitHandle y espera en otro, para lo que determina el intervalo de tiempo de espera como TimeSpan y especifica si se sale del dominio de sincronización para el contexto antes de entrar en la espera.Signals one WaitHandle and waits on another, specifying the time-out interval as a TimeSpan and specifying whether to exit the synchronization domain for the context before entering the wait.

SignalAndWait(WaitHandle, WaitHandle) SignalAndWait(WaitHandle, WaitHandle) SignalAndWait(WaitHandle, WaitHandle) SignalAndWait(WaitHandle, WaitHandle)

Señala un WaitHandle y espera en otro.Signals one WaitHandle and waits on another.

public:
 static bool SignalAndWait(System::Threading::WaitHandle ^ toSignal, System::Threading::WaitHandle ^ toWaitOn);
public static bool SignalAndWait (System.Threading.WaitHandle toSignal, System.Threading.WaitHandle toWaitOn);
static member SignalAndWait : System.Threading.WaitHandle * System.Threading.WaitHandle -> bool
Public Shared Function SignalAndWait (toSignal As WaitHandle, toWaitOn As WaitHandle) As Boolean

Parámetros

toSignal
WaitHandle WaitHandle WaitHandle WaitHandle

WaitHandle que se va a señalar.The WaitHandle to signal.

toWaitOn
WaitHandle WaitHandle WaitHandle WaitHandle

WaitHandle en donde se va a esperar.The WaitHandle to wait on.

Devoluciones

true si la señal y la espera finalizan correctamente; si la espera no finaliza, el método no devuelve ningún resultado.true if both the signal and the wait complete successfully; if the wait does not complete, the method does not return.

Excepciones

toSignal es null.toSignal is null.

O bien-or- toWaitOn es null.toWaitOn is null.

Se llamó al método en un subproceso con STAThreadAttribute.The method was called on a thread that has STAThreadAttribute.

No se admite este método en Windows 98 ni en Windows Millennium.This method is not supported on Windows 98 or Windows Millennium Edition.

toSignal es un semáforo y su contador ya está completo.toSignal is a semaphore, and it already has a full count.

La espera finalizó porque un subproceso se cierra sin liberar una exclusión mutua.The wait completed because a thread exited without releasing a mutex. Esta excepción no se produce en Windows 98 o en Windows Millennium Edition.This exception is not thrown on Windows 98 or Windows Millennium Edition.

Ejemplos

En el ejemplo de código siguiente SignalAndWait(WaitHandle, WaitHandle) se usa la sobrecarga del método para permitir que el subproceso principal señale un subproceso bloqueado y, a continuación, espere hasta que el subproceso finalice una tarea.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.

El ejemplo inicia cinco subprocesos, permite que se bloqueen en EventWaitHandle un EventResetMode.AutoReset creado con la marca y, a continuación, libera un subproceso cada vez que el usuario presiona la tecla entrar.The example starts five threads, allows them to block on an EventWaitHandle created with the EventResetMode.AutoReset flag, and then releases one thread each time the user presses the ENTER key. A continuación, el ejemplo pone en cola otros cinco subprocesos y EventWaitHandle los libera mediante EventResetMode.ManualReset un creado con la marca.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
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

Comentarios

No se garantiza que esta operación sea atómica.This operation is not guaranteed to be atomic. Después de que el subproceso toSignal actual señale, pero antes de toWaitOnque espere, un subproceso que se está toWaitOn ejecutando en otro procesador podría señalizar o esperar.After the current thread signals toSignal but before it waits on toWaitOn, a thread that is running on another processor might signal toWaitOn or wait on it.

SignalAndWait(WaitHandle, WaitHandle, Int32, Boolean) SignalAndWait(WaitHandle, WaitHandle, Int32, Boolean) SignalAndWait(WaitHandle, WaitHandle, Int32, Boolean) SignalAndWait(WaitHandle, WaitHandle, Int32, Boolean)

Señala un WaitHandle y espera en otro, para lo que determina un intervalo de tiempo de espera como entero con signo de 32 bits y especifica si se sale del dominio de sincronización para el contexto antes de entrar en la espera.Signals one WaitHandle and waits on another, specifying a time-out interval as a 32-bit signed integer and specifying whether to exit the synchronization domain for the context before entering the wait.

public:
 static bool SignalAndWait(System::Threading::WaitHandle ^ toSignal, System::Threading::WaitHandle ^ toWaitOn, int millisecondsTimeout, bool exitContext);
public static bool SignalAndWait (System.Threading.WaitHandle toSignal, System.Threading.WaitHandle toWaitOn, int millisecondsTimeout, bool exitContext);
static member SignalAndWait : System.Threading.WaitHandle * System.Threading.WaitHandle * int * bool -> bool
Public Shared Function SignalAndWait (toSignal As WaitHandle, toWaitOn As WaitHandle, millisecondsTimeout As Integer, exitContext As Boolean) As Boolean

Parámetros

toSignal
WaitHandle WaitHandle WaitHandle WaitHandle

WaitHandle que se va a señalar.The WaitHandle to signal.

toWaitOn
WaitHandle WaitHandle WaitHandle WaitHandle

WaitHandle en donde se va a esperar.The WaitHandle to wait on.

millisecondsTimeout
Int32 Int32 Int32 Int32

Entero que representa el intervalo que se va a esperar.An integer that represents the interval to wait. Si el valor es Infinite, esto es, -1, la espera es infinita.If the value is Infinite, that is, -1, the wait is infinite.

exitContext
Boolean Boolean Boolean Boolean

true para salir del dominio de sincronización del contexto antes de la espera (en caso de encontrarse en un contexto sincronizado) y volver a adquirirlo más tarde; de lo contrario, false.true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it afterward; otherwise, false.

Devoluciones

Es true si la señal y la espera finalizan correctamente, o false si la señal finaliza pero el tiempo de la espera se agota.true if both the signal and the wait completed successfully, or false if the signal completed but the wait timed out.

Excepciones

toSignal es null.toSignal is null.

O bien-or- toWaitOn es null.toWaitOn is null.

Se llama al método en un subproceso con STAThreadAttribute.The method is called on a thread that has STAThreadAttribute.

No se admite este método en Windows 98 ni en Windows Millennium.This method is not supported on Windows 98 or Windows Millennium Edition.

No se puede señalar a WaitHandle porque se superaría su recuento máximo.The WaitHandle cannot be signaled because it would exceed its maximum count.

millisecondsTimeout es un número negativo distinto de-1, que representa un tiempo de espera infinito.millisecondsTimeout is a negative number other than -1, which represents an infinite time-out.

La espera finalizó porque un subproceso se cierra sin liberar una exclusión mutua.The wait completed because a thread exited without releasing a mutex. Esta excepción no se produce en Windows 98 o en Windows Millennium Edition.This exception is not thrown on Windows 98 or Windows Millennium Edition.

Comentarios

No se garantiza que esta operación sea atómica.This operation is not guaranteed to be atomic. Después de que el subproceso toSignal actual señale, pero antes de toWaitOnque espere, un subproceso que se está toWaitOn ejecutando en otro procesador podría señalizar o esperar.After the current thread signals toSignal but before it waits on toWaitOn, a thread that is running on another processor might signal toWaitOn or wait on it.

Si millisecondsTimeout es cero, el método no se bloquea.If millisecondsTimeout is zero, the method does not block. Comprueba el estado de toWaitOn y vuelve inmediatamente.It tests the state of the toWaitOn and returns immediately.

Notas sobre la salida del contextoNotes on Exiting the Context

El exitContext parámetro no tiene ningún efecto a SignalAndWait menos que se llame al método desde dentro de un contexto administrado no predeterminado.The exitContext parameter has no effect unless the SignalAndWait method is called from inside a nondefault managed context. Esto puede ocurrir si el subproceso se encuentra dentro de una llamada a una instancia de una ContextBoundObjectclase derivada de.This can happen if your thread is inside a call to an instance of a class derived from ContextBoundObject. Incluso si está ejecutando un método en una clase que no deriva de ContextBoundObject, como String, puede estar en un contexto no predeterminado si un ContextBoundObject está en la pila en el dominio de aplicación actual.Even if you are currently executing a method on a class that does not derive from ContextBoundObject, like String, you can be in a nondefault context if a ContextBoundObject is on your stack in the current application domain.

Cuando el código se ejecuta en un contexto no predeterminado, la especificación true de para exitContext hace que el subproceso salga del contexto administrado no predeterminado (es decir, que pase al contexto predeterminado) antes de ejecutar el SignalAndWait método.When your code is executing in a nondefault context, specifying true for exitContext causes the thread to exit the nondefault managed context (that is, to transition to the default context) before executing the SignalAndWait method. El subproceso vuelve al contexto no predeterminado original después de que se complete SignalAndWait la llamada al método.The thread returns to the original nondefault context after the call to the SignalAndWait method completes.

Esto puede ser útil cuando la clase enlazada a un SynchronizationAttributecontexto tiene.This can be useful when the context-bound class has SynchronizationAttribute. En ese caso, todas las llamadas a miembros de la clase se sincronizan automáticamente y el dominio de sincronización es el cuerpo completo del código para la clase.In that case, all calls to members of the class are automatically synchronized, and the synchronization domain is the entire body of code for the class. Si el código de la pila de llamadas de un miembro SignalAndWait llama al método true y exitContextespecifica para, el subproceso sale del dominio de sincronización, lo que permite que un subproceso bloqueado en una llamada a cualquier miembro del objeto continúe.If code in the call stack of a member calls the SignalAndWait method and specifies true for exitContext, the thread exits the synchronization domain, allowing a thread that is blocked on a call to any member of the object to proceed. Cuando el SignalAndWait método devuelve, el subproceso que realizó la llamada debe esperar para volver a entrar en el dominio de sincronización.When the SignalAndWait method returns, the thread that made the call must wait to reenter the synchronization domain.

SignalAndWait(WaitHandle, WaitHandle, TimeSpan, Boolean) SignalAndWait(WaitHandle, WaitHandle, TimeSpan, Boolean) SignalAndWait(WaitHandle, WaitHandle, TimeSpan, Boolean) SignalAndWait(WaitHandle, WaitHandle, TimeSpan, Boolean)

Señala un WaitHandle y espera en otro, para lo que determina el intervalo de tiempo de espera como TimeSpan y especifica si se sale del dominio de sincronización para el contexto antes de entrar en la espera.Signals one WaitHandle and waits on another, specifying the time-out interval as a TimeSpan and specifying whether to exit the synchronization domain for the context before entering the wait.

public:
 static bool SignalAndWait(System::Threading::WaitHandle ^ toSignal, System::Threading::WaitHandle ^ toWaitOn, TimeSpan timeout, bool exitContext);
public static bool SignalAndWait (System.Threading.WaitHandle toSignal, System.Threading.WaitHandle toWaitOn, TimeSpan timeout, bool exitContext);
static member SignalAndWait : System.Threading.WaitHandle * System.Threading.WaitHandle * TimeSpan * bool -> bool
Public Shared Function SignalAndWait (toSignal As WaitHandle, toWaitOn As WaitHandle, timeout As TimeSpan, exitContext As Boolean) As Boolean

Parámetros

toSignal
WaitHandle WaitHandle WaitHandle WaitHandle

WaitHandle que se va a señalar.The WaitHandle to signal.

toWaitOn
WaitHandle WaitHandle WaitHandle WaitHandle

WaitHandle en donde se va a esperar.The WaitHandle to wait on.

timeout
TimeSpan TimeSpan TimeSpan TimeSpan

TimeSpan que representa el intervalo que se va a esperar.A TimeSpan that represents the interval to wait. Si el valor es -1, la espera es infinita.If the value is -1, the wait is infinite.

exitContext
Boolean Boolean Boolean Boolean

true para salir del dominio de sincronización del contexto antes de la espera (en caso de encontrarse en un contexto sincronizado) y volver a adquirirlo más tarde; de lo contrario, false.true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it afterward; otherwise, false.

Devoluciones

Es true si la señal y la espera finalizan correctamente, o false si la señal finaliza pero el tiempo de la espera se agota.true if both the signal and the wait completed successfully, or false if the signal completed but the wait timed out.

Excepciones

toSignal es null.toSignal is null.

O bien-or- toWaitOn es null.toWaitOn is null.

Se llamó al método en un subproceso con STAThreadAttribute.The method was called on a thread that has STAThreadAttribute.

No se admite este método en Windows 98 ni en Windows Millennium.This method is not supported on Windows 98 or Windows Millennium Edition.

toSignal es un semáforo y su contador ya está completo.toSignal is a semaphore, and it already has a full count.

timeout se evalúa como un número negativo de milisegundos distinto de -1.timeout evaluates to a negative number of milliseconds other than -1.

O bien-or- timeout es mayor que MaxValue.timeout is greater than MaxValue.

La espera finalizó porque un subproceso se cierra sin liberar una exclusión mutua.The wait completed because a thread exited without releasing a mutex. Esta excepción no se produce en Windows 98 o en Windows Millennium Edition.This exception is not thrown on Windows 98 or Windows Millennium Edition.

Comentarios

No se garantiza que esta operación sea atómica.This operation is not guaranteed to be atomic. Después de que el subproceso toSignal actual señale, pero antes de toWaitOnque espere, un subproceso que se está toWaitOn ejecutando en otro procesador podría señalizar o esperar.After the current thread signals toSignal but before it waits on toWaitOn, a thread that is running on another processor might signal toWaitOn or wait on it.

El valor máximo de timeout es Int32.MaxValue.The maximum value for timeout is Int32.MaxValue.

Si timeout es cero, el método no se bloquea.If timeout is zero, the method does not block. Comprueba el estado de toWaitOn y vuelve inmediatamente.It tests the state of the toWaitOn and returns immediately.

Notas sobre la salida del contextoNotes on Exiting the Context

El exitContext parámetro no tiene ningún efecto a SignalAndWait menos que se llame al método desde dentro de un contexto administrado no predeterminado.The exitContext parameter has no effect unless the SignalAndWait method is called from inside a nondefault managed context. Esto puede ocurrir si el subproceso se encuentra dentro de una llamada a una instancia de una ContextBoundObjectclase derivada de.This can happen if your thread is inside a call to an instance of a class derived from ContextBoundObject. Incluso si está ejecutando un método en una clase que no deriva de ContextBoundObject, como String, puede estar en un contexto no predeterminado si un ContextBoundObject está en la pila en el dominio de aplicación actual.Even if you are currently executing a method on a class that does not derive from ContextBoundObject, like String, you can be in a nondefault context if a ContextBoundObject is on your stack in the current application domain.

Cuando el código se ejecuta en un contexto no predeterminado, la especificación true de para exitContext hace que el subproceso salga del contexto administrado no predeterminado (es decir, que pase al contexto predeterminado) antes de ejecutar el SignalAndWait método.When your code is executing in a nondefault context, specifying true for exitContext causes the thread to exit the nondefault managed context (that is, to transition to the default context) before executing the SignalAndWait method. El subproceso vuelve al contexto no predeterminado original después de que se complete SignalAndWait la llamada al método.The thread returns to the original nondefault context after the call to the SignalAndWait method completes.

Esto puede ser útil cuando la clase enlazada a un SynchronizationAttributecontexto tiene.This can be useful when the context-bound class has SynchronizationAttribute. En ese caso, todas las llamadas a miembros de la clase se sincronizan automáticamente y el dominio de sincronización es el cuerpo completo del código para la clase.In that case, all calls to members of the class are automatically synchronized, and the synchronization domain is the entire body of code for the class. Si el código de la pila de llamadas de un miembro SignalAndWait llama al método true y exitContextespecifica para, el subproceso sale del dominio de sincronización, lo que permite que un subproceso bloqueado en una llamada a cualquier miembro del objeto continúe.If code in the call stack of a member calls the SignalAndWait method and specifies true for exitContext, the thread exits the synchronization domain, allowing a thread that is blocked on a call to any member of the object to proceed. Cuando el SignalAndWait método devuelve, el subproceso que realizó la llamada debe esperar para volver a entrar en el dominio de sincronización.When the SignalAndWait method returns, the thread that made the call must wait to reenter the synchronization domain.

Se aplica a