ThreadPool.RegisterWaitForSingleObject Metodo

Definizione

Registra un delegato in attesa di un WaitHandle.

Overload

RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean)

Registra un delegato per l'attesa di un oggetto WaitHandle, specificando un intero senza segno a 32 bit per il timeout in millisecondi.

RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean)

Registra un delegato per l'attesa di un oggetto WaitHandle, specificando un valore TimeSpan per il timeout.

RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean)

Registra un delegato per l'attesa di un oggetto WaitHandle, specificando un valore intero con segno a 32 bit per il timeout in millisecondi.

RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean)

Registra un delegato per l'attesa di un oggetto WaitHandle, specificando un valore intero con segno a 64 bit per il timeout in millisecondi.

RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean)

Importante

Questa API non è conforme a CLS.

Registra un delegato per l'attesa di un oggetto WaitHandle, specificando un intero senza segno a 32 bit per il timeout in millisecondi.

public:
 static System::Threading::RegisteredWaitHandle ^ RegisterWaitForSingleObject(System::Threading::WaitHandle ^ waitObject, System::Threading::WaitOrTimerCallback ^ callBack, System::Object ^ state, System::UInt32 millisecondsTimeOutInterval, bool executeOnlyOnce);
[System.CLSCompliant(false)]
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static System.Threading.RegisteredWaitHandle RegisterWaitForSingleObject (System.Threading.WaitHandle waitObject, System.Threading.WaitOrTimerCallback callBack, object? state, uint millisecondsTimeOutInterval, bool executeOnlyOnce);
[System.CLSCompliant(false)]
public static System.Threading.RegisteredWaitHandle RegisterWaitForSingleObject (System.Threading.WaitHandle waitObject, System.Threading.WaitOrTimerCallback callBack, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce);
[System.CLSCompliant(false)]
public static System.Threading.RegisteredWaitHandle RegisterWaitForSingleObject (System.Threading.WaitHandle waitObject, System.Threading.WaitOrTimerCallback callBack, object? state, uint millisecondsTimeOutInterval, bool executeOnlyOnce);
[<System.CLSCompliant(false)>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member RegisterWaitForSingleObject : System.Threading.WaitHandle * System.Threading.WaitOrTimerCallback * obj * uint32 * bool -> System.Threading.RegisteredWaitHandle
[<System.CLSCompliant(false)>]
static member RegisterWaitForSingleObject : System.Threading.WaitHandle * System.Threading.WaitOrTimerCallback * obj * uint32 * bool -> System.Threading.RegisteredWaitHandle
Public Shared Function RegisterWaitForSingleObject (waitObject As WaitHandle, callBack As WaitOrTimerCallback, state As Object, millisecondsTimeOutInterval As UInteger, executeOnlyOnce As Boolean) As RegisteredWaitHandle

Parametri

waitObject
WaitHandle

WaitHandle da registrare. Usare una classe WaitHandle diversa da Mutex.

callBack
WaitOrTimerCallback

Delegato WaitOrTimerCallback da chiamare quando il parametro waitObject riceve un segnale.

state
Object

Oggetto passato al delegato.

millisecondsTimeOutInterval
UInt32

Timeout in millisecondi. Se il parametro millisecondsTimeOutInterval è pari a 0 (zero), la funzione verifica lo stato dell'oggetto e restituisce immediatamente un valore. Se millisecondsTimeOutInterval è -1, l'intervallo di timeout della funzione non termina mai.

executeOnlyOnce
Boolean

Viene restituito true per indicare che il thread non attenderà più in base al parametro waitObject dopo la chiamata al delegato; false per indicare che il timer viene reimpostato ogni volta che l'operazione di attesa viene completata fino all'annullamento della registrazione dell'attesa.

Restituisce

Oggetto RegisteredWaitHandle che può essere usato per annullare l'operazione di attesa registrata.

Attributi

Eccezioni

Il parametro millisecondsTimeOutInterval è minore di -1.

Esempio

Nell'esempio seguente viene illustrato come utilizzare il RegisterWaitForSingleObject metodo per eseguire un metodo di callback specificato quando viene segnalato un handle di attesa specificato. In questo esempio il metodo di callback è WaitProce l'handle di attesa è .AutoResetEvent

Nell'esempio viene definita una TaskInfo classe che contiene le informazioni passate al callback quando viene eseguito. Nell'esempio viene creato un TaskInfo oggetto e vengono assegnati alcuni dati stringa. L'oggetto restituito dal RegisterWaitForSingleObject metodo viene assegnato al Handle campo dell'oggetto TaskInfo in modo che il metodo di callback abbia accesso a RegisteredWaitHandle.RegisteredWaitHandle

Oltre a specificare TaskInfo come oggetto da passare al metodo di callback, la chiamata al RegisterWaitForSingleObject metodo specifica che AutoResetEvent l'attività attenderà, un WaitOrTimerCallback delegato che rappresenta il WaitProc metodo di callback, un intervallo di timeout di un secondo e più callback.

Quando il thread principale segnala l'oggetto AutoResetEvent chiamando il relativo Set metodo, viene richiamato il WaitOrTimerCallback delegato. Il WaitProc metodo verifica RegisteredWaitHandle se si è verificato un timeout. Se il callback è stato richiamato perché l'handle di attesa è stato segnalato, il WaitProc metodo annulla la registrazione di RegisteredWaitHandle, arrestando altri callback. In caso di timeout, l'attività continua ad attendere. Il WaitProc metodo termina stampando un messaggio nella console.

using namespace System;
using namespace System::Threading;

// TaskInfo contains data that will be passed to the callback
// method.
public ref class TaskInfo
{
public:
   TaskInfo()
   {
      Handle = nullptr;
      OtherInfo = "default";
   }

   RegisteredWaitHandle^ Handle;
   String^ OtherInfo;
};

ref class Example
{
public:

   // The callback method executes when the registered wait times out,
   // or when the WaitHandle (in this case AutoResetEvent) is signaled.
   // WaitProc unregisters the WaitHandle the first time the event is 
   // signaled.
   static void WaitProc( Object^ state, bool timedOut )
   {
      
      // The state Object must be cast to the correct type, because the
      // signature of the WaitOrTimerCallback delegate specifies type
      // Object.
      TaskInfo^ ti = static_cast<TaskInfo^>(state);
      String^ cause = "TIMED OUT";
      if (  !timedOut )
      {
         cause = "SIGNALED";
         
         // If the callback method executes because the WaitHandle is
         // signaled, stop future execution of the callback method
         // by unregistering the WaitHandle.
         if ( ti->Handle != nullptr )
                  ti->Handle->Unregister( nullptr );
      }

      Console::WriteLine( "WaitProc( {0}) executes on thread {1}; cause = {2}.", ti->OtherInfo, Thread::CurrentThread->GetHashCode(), cause );
   }

};

int main()
{
   
   // The main thread uses AutoResetEvent to signal the
   // registered wait handle, which executes the callback
   // method.
   AutoResetEvent^ ev = gcnew AutoResetEvent( false );
   TaskInfo^ ti = gcnew TaskInfo;
   ti->OtherInfo = "First task";
   
   // The TaskInfo for the task includes the registered wait
   // handle returned by RegisterWaitForSingleObject.  This
   // allows the wait to be terminated when the object has
   // been signaled once (see WaitProc).
   ti->Handle = ThreadPool::RegisterWaitForSingleObject( ev, gcnew WaitOrTimerCallback( Example::WaitProc ), ti, 1000, false );
   
   // The main thread waits three seconds, to demonstrate the
   // time-outs on the queued thread, and then signals.
   Thread::Sleep( 3100 );
   Console::WriteLine( "Main thread signals." );
   ev->Set();
   
   // The main thread sleeps, which should give the callback
   // method time to execute.  If you comment out this line, the
   // program usually ends before the ThreadPool thread can execute.
   Thread::Sleep( 1000 );
   
   // If you start a thread yourself, you can wait for it to end
   // by calling Thread::Join.  This option is not available with 
   // thread pool threads.
   return 0;
}
using System;
using System.Threading;

// TaskInfo contains data that will be passed to the callback
// method.
public class TaskInfo {
    public RegisteredWaitHandle Handle = null;
    public string OtherInfo = "default";
}

public class Example {
    public static void Main(string[] args) {
        // The main thread uses AutoResetEvent to signal the
        // registered wait handle, which executes the callback
        // method.
        AutoResetEvent ev = new AutoResetEvent(false);

        TaskInfo ti = new TaskInfo();
        ti.OtherInfo = "First task";
        // The TaskInfo for the task includes the registered wait
        // handle returned by RegisterWaitForSingleObject.  This
        // allows the wait to be terminated when the object has
        // been signaled once (see WaitProc).
        ti.Handle = ThreadPool.RegisterWaitForSingleObject(
            ev,
            new WaitOrTimerCallback(WaitProc),
            ti,
            1000,
            false
        );

        // The main thread waits three seconds, to demonstrate the
        // time-outs on the queued thread, and then signals.
        Thread.Sleep(3100);
        Console.WriteLine("Main thread signals.");
        ev.Set();

        // The main thread sleeps, which should give the callback
        // method time to execute.  If you comment out this line, the
        // program usually ends before the ThreadPool thread can execute.
        Thread.Sleep(1000);
        // If you start a thread yourself, you can wait for it to end
        // by calling Thread.Join.  This option is not available with 
        // thread pool threads.
    }
   
    // The callback method executes when the registered wait times out,
    // or when the WaitHandle (in this case AutoResetEvent) is signaled.
    // WaitProc unregisters the WaitHandle the first time the event is 
    // signaled.
    public static void WaitProc(object state, bool timedOut) {
        // The state object must be cast to the correct type, because the
        // signature of the WaitOrTimerCallback delegate specifies type
        // Object.
        TaskInfo ti = (TaskInfo) state;

        string cause = "TIMED OUT";
        if (!timedOut) {
            cause = "SIGNALED";
            // If the callback method executes because the WaitHandle is
            // signaled, stop future execution of the callback method
            // by unregistering the WaitHandle.
            if (ti.Handle != null)
                ti.Handle.Unregister(null);
        } 

        Console.WriteLine("WaitProc( {0} ) executes on thread {1}; cause = {2}.",
            ti.OtherInfo, 
            Thread.CurrentThread.GetHashCode().ToString(), 
            cause
        );
    }
}
Imports System.Threading

' TaskInfo contains data that will be passed to the callback
' method.
Public Class TaskInfo
    public Handle As RegisteredWaitHandle = Nothing
    public OtherInfo As String = "default"
End Class

Public Class Example

    <MTAThread> _
    Public Shared Sub Main()
        ' The main thread uses AutoResetEvent to signal the
        ' registered wait handle, which executes the callback
        ' method.
        Dim ev As New AutoResetEvent(false)

        Dim ti As New TaskInfo()
        ti.OtherInfo = "First task"
        ' The TaskInfo for the task includes the registered wait
        ' handle returned by RegisterWaitForSingleObject.  This
        ' allows the wait to be terminated when the object has
        ' been signaled once (see WaitProc).
        ti.Handle = ThreadPool.RegisterWaitForSingleObject( _
            ev, _
            New WaitOrTimerCallback(AddressOf WaitProc), _
            ti, _
            1000, _
            false _
        )

        ' The main thread waits about three seconds, to demonstrate 
        ' the time-outs on the queued task, and then signals.
        Thread.Sleep(3100)
        Console.WriteLine("Main thread signals.")
        ev.Set()

        ' The main thread sleeps, which should give the callback
        ' method time to execute.  If you comment out this line, the
        ' program usually ends before the ThreadPool thread can execute.
        Thread.Sleep(1000)
        ' If you start a thread yourself, you can wait for it to end
        ' by calling Thread.Join.  This option is not available with 
        ' thread pool threads.
    End Sub
   
    ' The callback method executes when the registered wait times out,
    ' or when the WaitHandle (in this case AutoResetEvent) is signaled.
    ' WaitProc unregisters the WaitHandle the first time the event is 
    ' signaled.
    Public Shared Sub WaitProc(state As Object, timedOut As Boolean)
        ' The state object must be cast to the correct type, because the
        ' signature of the WaitOrTimerCallback delegate specifies type
        ' Object.
        Dim ti As TaskInfo = CType(state, TaskInfo)

        Dim cause As String = "TIMED OUT"
        If Not timedOut Then
            cause = "SIGNALED"
            ' If the callback method executes because the WaitHandle is
            ' signaled, stop future execution of the callback method
            ' by unregistering the WaitHandle.
            If Not ti.Handle Is Nothing Then
                ti.Handle.Unregister(Nothing)
            End If
        End If 

        Console.WriteLine("WaitProc( {0} ) executes on thread {1}; cause = {2}.", _
            ti.OtherInfo, _
            Thread.CurrentThread.GetHashCode().ToString(), _
            cause _
        )
    End Sub
End Class

Commenti

Al termine dell'utilizzo dell'oggetto RegisteredWaitHandle restituito da questo metodo, chiamare il relativo RegisteredWaitHandle.Unregister metodo per rilasciare i riferimenti all'handle di attesa. È consigliabile chiamare sempre il RegisteredWaitHandle.Unregister metodo , anche se si specifica true per executeOnlyOnce. Garbage Collection funziona in modo più efficiente se si chiama il RegisteredWaitHandle.Unregister metodo anziché a seconda del finalizzatore dell'handle di attesa registrato.

Il RegisterWaitForSingleObject metodo accoda il delegato specificato al pool di thread. Un thread di lavoro eseguirà il delegato quando si verifica uno dei seguenti:

  • L'oggetto specificato si trova nello stato segnalato.
  • Intervallo di timeout trascorso.

Il RegisterWaitForSingleObject metodo controlla lo stato corrente dell'oggetto WaitHandlespecificato. Se lo stato dell'oggetto non è firmato, il metodo registra un'operazione di attesa. L'operazione di attesa viene eseguita da un thread dal pool di thread. Il delegato viene eseguito da un thread di lavoro quando lo stato dell'oggetto viene segnalato o l'intervallo di timeout scade. Se il timeOutInterval parametro non è 0 (zero) e il executeOnlyOnce parametro è false, il timer viene reimpostato ogni volta che l'evento viene segnalato o l'intervallo di timeout scade.

Importante

L'uso di per MutexwaitObject non fornisce l'esclusione reciproca per i callback perché l'API Di Windows sottostante usa il flag predefinito WT_EXECUTEDEFAULT , quindi ogni callback viene inviato in un thread del pool di thread separato. Invece di , Mutexusare un Semaphore oggetto con un conteggio massimo di 1.

Per annullare l'operazione di attesa, chiamare il RegisteredWaitHandle.Unregister metodo .

Il thread di attesa usa la funzione Win32 WaitForMultipleObjects per monitorare le operazioni di attesa registrate. Pertanto, se è necessario usare lo stesso handle del sistema operativo nativo in più chiamate a RegisterWaitForSingleObject, è necessario duplicare l'handle usando la funzione Win32 DuplicateHandle . Si noti che non è consigliabile eseguire l'impulso di un oggetto evento passato a RegisterWaitForSingleObjectperché il thread di attesa potrebbe non rilevare che l'evento viene segnalato prima della reimpostazione.

Prima di restituire , la funzione modifica lo stato di alcuni tipi di oggetti di sincronizzazione. La modifica si verifica solo per l'oggetto il cui stato segnalato ha causato la soddisfazione della condizione di attesa. Ad esempio, il conteggio di un semaforo viene ridotto di uno.

Vedi anche

Si applica a

RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean)

Registra un delegato per l'attesa di un oggetto WaitHandle, specificando un valore TimeSpan per il timeout.

public:
 static System::Threading::RegisteredWaitHandle ^ RegisterWaitForSingleObject(System::Threading::WaitHandle ^ waitObject, System::Threading::WaitOrTimerCallback ^ callBack, System::Object ^ state, TimeSpan timeout, bool executeOnlyOnce);
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static System.Threading.RegisteredWaitHandle RegisterWaitForSingleObject (System.Threading.WaitHandle waitObject, System.Threading.WaitOrTimerCallback callBack, object? state, TimeSpan timeout, bool executeOnlyOnce);
public static System.Threading.RegisteredWaitHandle RegisterWaitForSingleObject (System.Threading.WaitHandle waitObject, System.Threading.WaitOrTimerCallback callBack, object state, TimeSpan timeout, bool executeOnlyOnce);
public static System.Threading.RegisteredWaitHandle RegisterWaitForSingleObject (System.Threading.WaitHandle waitObject, System.Threading.WaitOrTimerCallback callBack, object? state, TimeSpan timeout, bool executeOnlyOnce);
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member RegisterWaitForSingleObject : System.Threading.WaitHandle * System.Threading.WaitOrTimerCallback * obj * TimeSpan * bool -> System.Threading.RegisteredWaitHandle
static member RegisterWaitForSingleObject : System.Threading.WaitHandle * System.Threading.WaitOrTimerCallback * obj * TimeSpan * bool -> System.Threading.RegisteredWaitHandle
Public Shared Function RegisterWaitForSingleObject (waitObject As WaitHandle, callBack As WaitOrTimerCallback, state As Object, timeout As TimeSpan, executeOnlyOnce As Boolean) As RegisteredWaitHandle

Parametri

waitObject
WaitHandle

WaitHandle da registrare. Usare una classe WaitHandle diversa da Mutex.

callBack
WaitOrTimerCallback

Delegato WaitOrTimerCallback da chiamare quando il parametro waitObject riceve un segnale.

state
Object

Oggetto passato al delegato.

timeout
TimeSpan

Il timeout rappresentato da un valore TimeSpan. Se timeout è pari a 0 (zero), la funzione verifica lo stato dell'oggetto e restituisce immediatamente un valore. Se timeout è -1, l'intervallo di timeout della funzione non termina mai.

executeOnlyOnce
Boolean

Viene restituito true per indicare che il thread non attenderà più in base al parametro waitObject dopo la chiamata al delegato; false per indicare che il timer viene reimpostato ogni volta che l'operazione di attesa viene completata fino all'annullamento della registrazione dell'attesa.

Restituisce

RegisteredWaitHandle che incapsula l'handle nativo.

Attributi

Eccezioni

Il parametro timeout è minore di -1.

Il timeout parametro è maggiore di Int32.MaxValue.

Commenti

Al termine dell'utilizzo dell'oggetto RegisteredWaitHandle restituito da questo metodo, chiamare il relativo RegisteredWaitHandle.Unregister metodo per rilasciare i riferimenti all'handle di attesa. È consigliabile chiamare sempre il RegisteredWaitHandle.Unregister metodo , anche se si specifica true per executeOnlyOnce. Garbage Collection funziona in modo più efficiente se si chiama il RegisteredWaitHandle.Unregister metodo anziché a seconda del finalizzatore dell'handle di attesa registrato.

Il RegisterWaitForSingleObject metodo accoda il delegato specificato al pool di thread. Un thread di lavoro eseguirà il delegato quando si verifica uno dei seguenti:

  • L'oggetto specificato si trova nello stato segnalato.
  • Intervallo di timeout trascorso.

Il RegisterWaitForSingleObject metodo controlla lo stato corrente dell'oggetto WaitHandlespecificato. Se lo stato dell'oggetto non è firmato, il metodo registra un'operazione di attesa. L'operazione di attesa viene eseguita da un thread dal pool di thread. Il delegato viene eseguito da un thread di lavoro quando lo stato dell'oggetto viene segnalato o l'intervallo di timeout scade. Se il timeOutInterval parametro non è 0 (zero) e il executeOnlyOnce parametro è false, il timer viene reimpostato ogni volta che l'evento viene segnalato o l'intervallo di timeout scade.

Importante

L'uso di per MutexwaitObject non fornisce l'esclusione reciproca per i callback perché l'API Di Windows sottostante usa il flag predefinito WT_EXECUTEDEFAULT , quindi ogni callback viene inviato in un thread del pool di thread separato. Invece di , Mutexusare un Semaphore oggetto con un conteggio massimo di 1.

Per annullare l'operazione di attesa, chiamare il RegisteredWaitHandle.Unregister metodo .

Il thread di attesa usa la funzione Win32 WaitForMultipleObjects per monitorare le operazioni di attesa registrate. Pertanto, se è necessario usare lo stesso handle del sistema operativo nativo in più chiamate a RegisterWaitForSingleObject, è necessario duplicare l'handle usando la funzione Win32 DuplicateHandle . Si noti che non è consigliabile eseguire l'impulso di un oggetto evento passato a RegisterWaitForSingleObjectperché il thread di attesa potrebbe non rilevare che l'evento viene segnalato prima della reimpostazione.

Prima di restituire , la funzione modifica lo stato di alcuni tipi di oggetti di sincronizzazione. La modifica si verifica solo per l'oggetto il cui stato segnalato ha causato la soddisfazione della condizione di attesa. Ad esempio, il conteggio di un semaforo viene ridotto di uno.

Vedi anche

Si applica a

RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean)

Registra un delegato per l'attesa di un oggetto WaitHandle, specificando un valore intero con segno a 32 bit per il timeout in millisecondi.

public:
 static System::Threading::RegisteredWaitHandle ^ RegisterWaitForSingleObject(System::Threading::WaitHandle ^ waitObject, System::Threading::WaitOrTimerCallback ^ callBack, System::Object ^ state, int millisecondsTimeOutInterval, bool executeOnlyOnce);
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static System.Threading.RegisteredWaitHandle RegisterWaitForSingleObject (System.Threading.WaitHandle waitObject, System.Threading.WaitOrTimerCallback callBack, object? state, int millisecondsTimeOutInterval, bool executeOnlyOnce);
public static System.Threading.RegisteredWaitHandle RegisterWaitForSingleObject (System.Threading.WaitHandle waitObject, System.Threading.WaitOrTimerCallback callBack, object state, int millisecondsTimeOutInterval, bool executeOnlyOnce);
public static System.Threading.RegisteredWaitHandle RegisterWaitForSingleObject (System.Threading.WaitHandle waitObject, System.Threading.WaitOrTimerCallback callBack, object? state, int millisecondsTimeOutInterval, bool executeOnlyOnce);
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member RegisterWaitForSingleObject : System.Threading.WaitHandle * System.Threading.WaitOrTimerCallback * obj * int * bool -> System.Threading.RegisteredWaitHandle
static member RegisterWaitForSingleObject : System.Threading.WaitHandle * System.Threading.WaitOrTimerCallback * obj * int * bool -> System.Threading.RegisteredWaitHandle
Public Shared Function RegisterWaitForSingleObject (waitObject As WaitHandle, callBack As WaitOrTimerCallback, state As Object, millisecondsTimeOutInterval As Integer, executeOnlyOnce As Boolean) As RegisteredWaitHandle

Parametri

waitObject
WaitHandle

WaitHandle da registrare. Usare una classe WaitHandle diversa da Mutex.

callBack
WaitOrTimerCallback

Delegato WaitOrTimerCallback da chiamare quando il parametro waitObject riceve un segnale.

state
Object

Oggetto passato al delegato.

millisecondsTimeOutInterval
Int32

Timeout in millisecondi. Se il parametro millisecondsTimeOutInterval è pari a 0 (zero), la funzione verifica lo stato dell'oggetto e restituisce immediatamente un valore. Se millisecondsTimeOutInterval è -1, l'intervallo di timeout della funzione non termina mai.

executeOnlyOnce
Boolean

Viene restituito true per indicare che il thread non attenderà più in base al parametro waitObject dopo la chiamata al delegato; false per indicare che il timer viene reimpostato ogni volta che l'operazione di attesa viene completata fino all'annullamento della registrazione dell'attesa.

Restituisce

RegisteredWaitHandle che incapsula l'handle nativo.

Attributi

Eccezioni

Il parametro millisecondsTimeOutInterval è minore di -1.

Commenti

Al termine dell'uso dell'oggetto RegisteredWaitHandle restituito da questo metodo, chiamare il RegisteredWaitHandle.Unregister metodo per rilasciare i riferimenti all'handle di attesa. È consigliabile chiamare sempre il RegisteredWaitHandle.Unregister metodo, anche se si specifica true per executeOnlyOnce. Garbage Collection funziona in modo più efficiente se si chiama il RegisteredWaitHandle.Unregister metodo anziché a seconda del finalizzatore di attesa registrato.

Il RegisterWaitForSingleObject metodo accoda il delegato specificato al pool di thread. Un thread di lavoro eseguirà il delegato quando si verifica una delle operazioni seguenti:

  • L'oggetto specificato si trova nello stato segnalato.
  • L'intervallo di timeout trascorso.

Il RegisterWaitForSingleObject metodo controlla lo stato corrente dell'oggetto WaitHandlespecificato. Se lo stato dell'oggetto non è firmato, il metodo registra un'operazione di attesa. L'operazione di attesa viene eseguita da un thread dal pool di thread. Il delegato viene eseguito da un thread di lavoro quando lo stato dell'oggetto viene segnalato o trascorso l'intervallo di timeout. Se il timeOutInterval parametro non è 0 (zero) e il parametro è false, il executeOnlyOnce timer viene reimpostato ogni volta che l'evento viene segnalato o l'intervallo di timeout trascorso.

Importante

L'uso di un Mutex for waitObject non fornisce l'esclusione reciproca per i callback perché l'API Windows sottostante usa il flag predefinito WT_EXECUTEDEFAULT , quindi ogni callback viene inviato in un thread di pool di thread separato. Anziché un oggetto , usare un MutexSemaphore con un numero massimo di 1.

Per annullare l'operazione di attesa, chiamare il RegisteredWaitHandle.Unregister metodo .

Il thread di attesa usa la funzione Win32 WaitForMultipleObjects per monitorare le operazioni di attesa registrate. Pertanto, se è necessario usare lo stesso handle del sistema operativo nativo in più chiamate a RegisterWaitForSingleObject, è necessario duplicare l'handle usando la funzione Win32 DuplicateHandle . Si noti che non è necessario eseguire l'impulso di un oggetto evento passato a RegisterWaitForSingleObject, perché il thread di attesa potrebbe non rilevare che l'evento viene segnalato prima della reimpostazione.

Prima di restituire, la funzione modifica lo stato di alcuni tipi di oggetti di sincronizzazione. La modifica si verifica solo per l'oggetto lo stato segnalato ha causato l'soddisfatta della condizione di attesa. Ad esempio, il conteggio di un semaforo è diminuito di uno.

Vedi anche

Si applica a

RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean)

Registra un delegato per l'attesa di un oggetto WaitHandle, specificando un valore intero con segno a 64 bit per il timeout in millisecondi.

public:
 static System::Threading::RegisteredWaitHandle ^ RegisterWaitForSingleObject(System::Threading::WaitHandle ^ waitObject, System::Threading::WaitOrTimerCallback ^ callBack, System::Object ^ state, long millisecondsTimeOutInterval, bool executeOnlyOnce);
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static System.Threading.RegisteredWaitHandle RegisterWaitForSingleObject (System.Threading.WaitHandle waitObject, System.Threading.WaitOrTimerCallback callBack, object? state, long millisecondsTimeOutInterval, bool executeOnlyOnce);
public static System.Threading.RegisteredWaitHandle RegisterWaitForSingleObject (System.Threading.WaitHandle waitObject, System.Threading.WaitOrTimerCallback callBack, object state, long millisecondsTimeOutInterval, bool executeOnlyOnce);
public static System.Threading.RegisteredWaitHandle RegisterWaitForSingleObject (System.Threading.WaitHandle waitObject, System.Threading.WaitOrTimerCallback callBack, object? state, long millisecondsTimeOutInterval, bool executeOnlyOnce);
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member RegisterWaitForSingleObject : System.Threading.WaitHandle * System.Threading.WaitOrTimerCallback * obj * int64 * bool -> System.Threading.RegisteredWaitHandle
static member RegisterWaitForSingleObject : System.Threading.WaitHandle * System.Threading.WaitOrTimerCallback * obj * int64 * bool -> System.Threading.RegisteredWaitHandle
Public Shared Function RegisterWaitForSingleObject (waitObject As WaitHandle, callBack As WaitOrTimerCallback, state As Object, millisecondsTimeOutInterval As Long, executeOnlyOnce As Boolean) As RegisteredWaitHandle

Parametri

waitObject
WaitHandle

WaitHandle da registrare. Usare una classe WaitHandle diversa da Mutex.

callBack
WaitOrTimerCallback

Delegato WaitOrTimerCallback da chiamare quando il parametro waitObject riceve un segnale.

state
Object

Oggetto passato al delegato.

millisecondsTimeOutInterval
Int64

Timeout in millisecondi. Se il parametro millisecondsTimeOutInterval è pari a 0 (zero), la funzione verifica lo stato dell'oggetto e restituisce immediatamente un valore. Se millisecondsTimeOutInterval è -1, l'intervallo di timeout della funzione non termina mai.

executeOnlyOnce
Boolean

Viene restituito true per indicare che il thread non attenderà più in base al parametro waitObject dopo la chiamata al delegato; false per indicare che il timer viene reimpostato ogni volta che l'operazione di attesa viene completata fino all'annullamento della registrazione dell'attesa.

Restituisce

RegisteredWaitHandle che incapsula l'handle nativo.

Attributi

Eccezioni

Il parametro millisecondsTimeOutInterval è minore di -1.

Commenti

Al termine dell'uso dell'oggetto RegisteredWaitHandle restituito da questo metodo, chiamare il RegisteredWaitHandle.Unregister metodo per rilasciare i riferimenti all'handle di attesa. È consigliabile chiamare sempre il RegisteredWaitHandle.Unregister metodo, anche se si specifica true per executeOnlyOnce. Garbage Collection funziona in modo più efficiente se si chiama il RegisteredWaitHandle.Unregister metodo anziché a seconda del finalizzatore di attesa registrato.

Il RegisterWaitForSingleObject metodo accoda il delegato specificato al pool di thread. Un thread di lavoro eseguirà il delegato quando si verifica una delle operazioni seguenti:

  • L'oggetto specificato si trova nello stato segnalato.
  • L'intervallo di timeout trascorso.

Il RegisterWaitForSingleObject metodo controlla lo stato corrente dell'oggetto WaitHandlespecificato. Se lo stato dell'oggetto non è firmato, il metodo registra un'operazione di attesa. L'operazione di attesa viene eseguita da un thread dal pool di thread. Il delegato viene eseguito da un thread di lavoro quando lo stato dell'oggetto viene segnalato o trascorso l'intervallo di timeout. Se il timeOutInterval parametro non è 0 (zero) e il parametro è false, il executeOnlyOnce timer viene reimpostato ogni volta che l'evento viene segnalato o l'intervallo di timeout trascorso.

Importante

L'uso di un Mutex for waitObject non fornisce l'esclusione reciproca per i callback perché l'API Windows sottostante usa il flag predefinito WT_EXECUTEDEFAULT , quindi ogni callback viene inviato in un thread di pool di thread separato. Anziché un oggetto , usare un MutexSemaphore con un numero massimo di 1.

Per annullare l'operazione di attesa, chiamare il RegisteredWaitHandle.Unregister metodo .

Il thread di attesa usa la funzione Win32 WaitForMultipleObjects per monitorare le operazioni di attesa registrate. Pertanto, se è necessario usare lo stesso handle del sistema operativo nativo in più chiamate a RegisterWaitForSingleObject, è necessario duplicare l'handle usando la funzione Win32 DuplicateHandle . Si noti che non è necessario eseguire l'impulso di un oggetto evento passato a RegisterWaitForSingleObject, perché il thread di attesa potrebbe non rilevare che l'evento viene segnalato prima della reimpostazione.

Prima di restituire, la funzione modifica lo stato di alcuni tipi di oggetti di sincronizzazione. La modifica si verifica solo per l'oggetto lo stato segnalato ha causato l'soddisfatta della condizione di attesa. Ad esempio, il conteggio di un semaforo è diminuito di uno.

Vedi anche

Si applica a