ThreadPool.RegisterWaitForSingleObject Método

Definição

Regista um delegado que está à espera de um WaitHandle.

Sobrecargas

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

Regista um delegado para esperar por um WaitHandle, especificando um inteiro sem sinal de 32 bits para o time-out em milissegundos.

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

Regista um delegado para esperar por um WaitHandle, especificando um TimeSpan valor para o time-out.

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

Regista um delegado para esperar por um WaitHandle, especificando um inteiro assinado de 32 bits para o time-out em milissegundos.

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

Regista um delegado para esperar por um WaitHandle, especificando um inteiro assinado de 64 bits para o time-out em milissegundos.

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

Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs

Importante

Esta API não está em conformidade com CLS.

Regista um delegado para esperar por um WaitHandle, especificando um inteiro sem sinal de 32 bits para o time-out em milissegundos.

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

Parâmetros

waitObject
WaitHandle

O WaitHandle registo. Use um WaitHandle outro que não Mutexseja .

callBack
WaitOrTimerCallback

O WaitOrTimerCallback delegado a chamar quando o waitObject parâmetro é sinalizado.

state
Object

O objetivo passou para o delegado.

millisecondsTimeOutInterval
UInt32

O tempo em milissegundos. Se o millisecondsTimeOutInterval parâmetro for 0 (zero), a função testa o estado do objeto e retorna imediatamente. Se millisecondsTimeOutInterval for -1, o intervalo de time-out da função nunca passa.

executeOnlyOnce
Boolean

true indicar que a thread deixará de esperar no waitObject parâmetro depois de o delegado ter sido chamado; false indicar que o temporizador é reiniciado sempre que a operação de espera é concluída até que a espera seja desregistada.

Devoluções

Isso RegisteredWaitHandle pode ser usado para cancelar a operação de espera registada.

Atributos

Exceções

O millisecondsTimeOutInterval parâmetro é inferior a -1.

Exemplos

O exemplo seguinte mostra como usar o RegisterWaitForSingleObject método para executar um método de callback especificado quando um handle de espera especificado é sinalizado. Neste exemplo, o método de callback é WaitProc, e a alça de espera é um AutoResetEvent.

O exemplo define uma TaskInfo classe para armazenar a informação que é passada para o callback quando este é executado. O exemplo cria um TaskInfo objeto e atribui-lhe alguns dados de cadeia. O RegisteredWaitHandle que é devolvido pelo RegisterWaitForSingleObject método é atribuído ao Handle campo do TaskInfo objeto de modo que o método de retorno tenha acesso ao RegisteredWaitHandle.

Além de especificar TaskInfo como objeto a passar para o método de callback, a chamada ao RegisterWaitForSingleObject método especifica que AutoResetEvent a tarefa irá esperar, um WaitOrTimerCallback delegado que representa o WaitProc método de callback, um intervalo de tempo de um segundo e múltiplos callbacks.

Quando o thread principal sinaliza o AutoResetEvent chamando o seu Set método, o WaitOrTimerCallback delegado é invocado. O WaitProc método testa RegisteredWaitHandle para determinar se ocorreu um time-out. Se o callback foi invocado porque o handler de espera foi sinalizado, o WaitProc método desregista o RegisteredWaitHandle, parando callbacks adicionais. No caso de um tempo morto, a tarefa continua a esperar. O WaitProc método termina imprimindo uma mensagem para a consola.

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

Observações

Quando terminares de usar o RegisteredWaitHandle que é devolvido por este método, chama o seu RegisteredWaitHandle.Unregister método para libertar referências ao handle de espera. Recomendamos que chame sempre o RegisteredWaitHandle.Unregister método, mesmo que especifique true para executeOnlyOnce. A recolha de lixo funciona de forma mais eficiente se chamares o RegisteredWaitHandle.Unregister método em vez de depender do finalizador do handle de espera registado.

O RegisterWaitForSingleObject método coloca o delegado especificado na fila para o pool de threads. Um thread de trabalho executará o delegado quando ocorrer uma das seguintes situações:

  • O objeto especificado está no estado sinalizado.
  • O intervalo de tempo expira.

O RegisterWaitForSingleObject método verifica o estado atual do objeto WaitHandleespecificado. Se o estado do objeto não estiver sinalizado, o método regista uma operação de espera. A operação de espera é realizada por um thread do pool de threads. O delegado é executado por uma thread de trabalho quando o estado do objeto se torna sinalizado ou o intervalo de tempo expira. Se o timeOutInterval parâmetro não for 0 (zero) e o executeOnlyOnce parâmetro for false, o temporizador é reiniciado sempre que o evento é sinalizado ou o intervalo de tempo expira.

Importante

Usar um Mutex para waitObject não proporciona exclusão mútua para os callbacks porque a API Windows subjacente usa a flag padrão WT_EXECUTEDEFAULT, pelo que cada callback é despachado num thread de pool separado. Em vez de um Mutex, use a Semaphore com contagem máxima de 1.

Para cancelar a operação de espera, chame o RegisteredWaitHandle.Unregister método.

O thread de espera utiliza a função Win32 WaitForMultipleObjects para monitorizar as operações de espera registadas. Portanto, se tiver de usar o mesmo handle nativo do sistema operativo em múltiplas chamadas para RegisterWaitForSingleObject, deve duplicar o handle usando a função Win32 DuplicateHandle . Note que não deve pulsar um objeto de evento passado para RegisterWaitForSingleObject, porque o thread de espera pode não detetar que o evento é sinalizado antes de ser reiniciado.

Antes de regressar, a função modifica o estado de alguns tipos de objetos de sincronização. A modificação ocorre apenas para o objeto cujo estado sinalizado fez com que a condição de espera fosse satisfeita. Por exemplo, a contagem de um semáforo é reduzida em um.

Ver também

Aplica-se a

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

Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs

Regista um delegado para esperar por um WaitHandle, especificando um TimeSpan valor para o time-out.

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

Parâmetros

waitObject
WaitHandle

O WaitHandle registo. Use um WaitHandle outro que não Mutexseja .

callBack
WaitOrTimerCallback

O WaitOrTimerCallback delegado a chamar quando o waitObject parâmetro é sinalizado.

state
Object

O objetivo passou para o delegado.

timeout
TimeSpan

O time-out representado por um TimeSpan. Se timeout for 0 (zero), a função testa o estado do objeto e retorna imediatamente. Se timeout for -1, o intervalo de time-out da função nunca passa.

executeOnlyOnce
Boolean

true indicar que a thread deixará de esperar no waitObject parâmetro depois de o delegado ter sido chamado; false indicar que o temporizador é reiniciado sempre que a operação de espera é concluída até que a espera seja desregistada.

Devoluções

O RegisteredWaitHandle que encapsula o nome nativo.

Atributos

Exceções

O timeout parâmetro é inferior a -1.

O timeout parâmetro é maior do que Int32.MaxValue.

Observações

Quando terminares de usar o RegisteredWaitHandle que é devolvido por este método, chama o seu RegisteredWaitHandle.Unregister método para libertar referências ao handle de espera. Recomendamos que chame sempre o RegisteredWaitHandle.Unregister método, mesmo que especifique true para executeOnlyOnce. A recolha de lixo funciona de forma mais eficiente se chamares o RegisteredWaitHandle.Unregister método em vez de depender do finalizador do handle de espera registado.

O RegisterWaitForSingleObject método coloca o delegado especificado na fila para o pool de threads. Um thread de trabalho executará o delegado quando ocorrer uma das seguintes situações:

  • O objeto especificado está no estado sinalizado.
  • O intervalo de tempo expira.

O RegisterWaitForSingleObject método verifica o estado atual do objeto WaitHandleespecificado. Se o estado do objeto não estiver sinalizado, o método regista uma operação de espera. A operação de espera é realizada por um thread do pool de threads. O delegado é executado por uma thread de trabalho quando o estado do objeto se torna sinalizado ou o intervalo de tempo expira. Se o timeOutInterval parâmetro não for 0 (zero) e o executeOnlyOnce parâmetro for false, o temporizador é reiniciado sempre que o evento é sinalizado ou o intervalo de tempo expira.

Importante

Usar um Mutex para waitObject não proporciona exclusão mútua para os callbacks porque a API Windows subjacente usa a flag padrão WT_EXECUTEDEFAULT, pelo que cada callback é despachado num thread de pool separado. Em vez de um Mutex, use a Semaphore com contagem máxima de 1.

Para cancelar a operação de espera, chame o RegisteredWaitHandle.Unregister método.

O thread de espera utiliza a função Win32 WaitForMultipleObjects para monitorizar as operações de espera registadas. Portanto, se tiver de usar o mesmo handle nativo do sistema operativo em múltiplas chamadas para RegisterWaitForSingleObject, deve duplicar o handle usando a função Win32 DuplicateHandle . Note que não deve pulsar um objeto de evento passado para RegisterWaitForSingleObject, porque o thread de espera pode não detetar que o evento é sinalizado antes de ser reiniciado.

Antes de regressar, a função modifica o estado de alguns tipos de objetos de sincronização. A modificação ocorre apenas para o objeto cujo estado sinalizado fez com que a condição de espera fosse satisfeita. Por exemplo, a contagem de um semáforo é reduzida em um.

Ver também

Aplica-se a

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

Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs

Regista um delegado para esperar por um WaitHandle, especificando um inteiro assinado de 32 bits para o time-out em milissegundos.

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

Parâmetros

waitObject
WaitHandle

O WaitHandle registo. Use um WaitHandle outro que não Mutexseja .

callBack
WaitOrTimerCallback

O WaitOrTimerCallback delegado a chamar quando o waitObject parâmetro é sinalizado.

state
Object

O objeto que é passado ao delegado.

millisecondsTimeOutInterval
Int32

O tempo em milissegundos. Se o millisecondsTimeOutInterval parâmetro for 0 (zero), a função testa o estado do objeto e retorna imediatamente. Se millisecondsTimeOutInterval for -1, o intervalo de time-out da função nunca passa.

executeOnlyOnce
Boolean

true indicar que a thread deixará de esperar no waitObject parâmetro depois de o delegado ter sido chamado; false indicar que o temporizador é reiniciado sempre que a operação de espera é concluída até que a espera seja desregistada.

Devoluções

O RegisteredWaitHandle que encapsula o nome nativo.

Atributos

Exceções

O millisecondsTimeOutInterval parâmetro é inferior a -1.

Observações

Quando terminares de usar o RegisteredWaitHandle que é devolvido por este método, chama o seu RegisteredWaitHandle.Unregister método para libertar referências ao handle de espera. Recomendamos que chame sempre o RegisteredWaitHandle.Unregister método, mesmo que especifique true para executeOnlyOnce. A recolha de lixo funciona de forma mais eficiente se chamares o RegisteredWaitHandle.Unregister método em vez de depender do finalizador do handle de espera registado.

O RegisterWaitForSingleObject método coloca o delegado especificado na fila para o pool de threads. Um thread de trabalho executará o delegado quando ocorrer uma das seguintes situações:

  • O objeto especificado está no estado sinalizado.
  • O intervalo de tempo expira.

O RegisterWaitForSingleObject método verifica o estado atual do objeto WaitHandleespecificado. Se o estado do objeto não estiver sinalizado, o método regista uma operação de espera. A operação de espera é realizada por um thread do pool de threads. O delegado é executado por uma thread de trabalho quando o estado do objeto se torna sinalizado ou o intervalo de tempo expira. Se o timeOutInterval parâmetro não for 0 (zero) e o executeOnlyOnce parâmetro for false, o temporizador é reiniciado sempre que o evento é sinalizado ou o intervalo de tempo expira.

Importante

Usar um Mutex para waitObject não proporciona exclusão mútua para os callbacks porque a API Windows subjacente usa a flag padrão WT_EXECUTEDEFAULT, pelo que cada callback é despachado num thread de pool separado. Em vez de um Mutex, use a Semaphore com contagem máxima de 1.

Para cancelar a operação de espera, chame o RegisteredWaitHandle.Unregister método.

O thread de espera utiliza a função Win32 WaitForMultipleObjects para monitorizar as operações de espera registadas. Portanto, se tiver de usar o mesmo handle nativo do sistema operativo em múltiplas chamadas para RegisterWaitForSingleObject, deve duplicar o handle usando a função Win32 DuplicateHandle . Note que não deve pulsar um objeto de evento passado para RegisterWaitForSingleObject, porque o thread de espera pode não detetar que o evento é sinalizado antes de ser reiniciado.

Antes de regressar, a função modifica o estado de alguns tipos de objetos de sincronização. A modificação ocorre apenas para o objeto cujo estado sinalizado fez com que a condição de espera fosse satisfeita. Por exemplo, a contagem de um semáforo é reduzida em um.

Ver também

Aplica-se a

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

Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs
Origem:
ThreadPoolWorkQueue.cs

Regista um delegado para esperar por um WaitHandle, especificando um inteiro assinado de 64 bits para o time-out em milissegundos.

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

Parâmetros

waitObject
WaitHandle

O WaitHandle registo. Use um WaitHandle outro que não Mutexseja .

callBack
WaitOrTimerCallback

O WaitOrTimerCallback delegado a chamar quando o waitObject parâmetro é sinalizado.

state
Object

O objetivo passou para o delegado.

millisecondsTimeOutInterval
Int64

O tempo em milissegundos. Se o millisecondsTimeOutInterval parâmetro for 0 (zero), a função testa o estado do objeto e retorna imediatamente. Se millisecondsTimeOutInterval for -1, o intervalo de time-out da função nunca passa.

executeOnlyOnce
Boolean

true indicar que a thread deixará de esperar no waitObject parâmetro depois de o delegado ter sido chamado; false indicar que o temporizador é reiniciado sempre que a operação de espera é concluída até que a espera seja desregistada.

Devoluções

O RegisteredWaitHandle que encapsula o nome nativo.

Atributos

Exceções

O millisecondsTimeOutInterval parâmetro é inferior a -1.

Observações

Quando terminares de usar o RegisteredWaitHandle que é devolvido por este método, chama o seu RegisteredWaitHandle.Unregister método para libertar referências ao handle de espera. Recomendamos que chame sempre o RegisteredWaitHandle.Unregister método, mesmo que especifique true para executeOnlyOnce. A recolha de lixo funciona de forma mais eficiente se chamares o RegisteredWaitHandle.Unregister método em vez de depender do finalizador do handle de espera registado.

O RegisterWaitForSingleObject método coloca o delegado especificado na fila para o pool de threads. Um thread de trabalho executará o delegado quando ocorrer uma das seguintes situações:

  • O objeto especificado está no estado sinalizado.
  • O intervalo de tempo expira.

O RegisterWaitForSingleObject método verifica o estado atual do objeto WaitHandleespecificado. Se o estado do objeto não estiver sinalizado, o método regista uma operação de espera. A operação de espera é realizada por um thread do pool de threads. O delegado é executado por uma thread de trabalho quando o estado do objeto se torna sinalizado ou o intervalo de tempo expira. Se o timeOutInterval parâmetro não for 0 (zero) e o executeOnlyOnce parâmetro for false, o temporizador é reiniciado sempre que o evento é sinalizado ou o intervalo de tempo expira.

Importante

Usar um Mutex para waitObject não proporciona exclusão mútua para os callbacks porque a API Windows subjacente usa a flag padrão WT_EXECUTEDEFAULT, pelo que cada callback é despachado num thread de pool separado. Em vez de um Mutex, use a Semaphore com contagem máxima de 1.

Para cancelar a operação de espera, chame o RegisteredWaitHandle.Unregister método.

O thread de espera utiliza a função Win32 WaitForMultipleObjects para monitorizar as operações de espera registadas. Portanto, se tiver de usar o mesmo handle nativo do sistema operativo em múltiplas chamadas para RegisterWaitForSingleObject, deve duplicar o handle usando a função Win32 DuplicateHandle . Note que não deve pulsar um objeto de evento passado para RegisterWaitForSingleObject, porque o thread de espera pode não detetar que o evento é sinalizado antes de ser reiniciado.

Antes de regressar, a função modifica o estado de alguns tipos de objetos de sincronização. A modificação ocorre apenas para o objeto cujo estado sinalizado fez com que a condição de espera fosse satisfeita. Por exemplo, a contagem de um semáforo é reduzida em um.

Ver também

Aplica-se a