WaitOrTimerCallback Délégué

Définition

Représente une méthode à appeler lorsqu'un WaitHandle est signalé ou expire.Represents a method to be called when a WaitHandle is signaled or times out.

public delegate void WaitOrTimerCallback(System::Object ^ state, bool timedOut);
[System.Runtime.InteropServices.ComVisible(true)]
public delegate void WaitOrTimerCallback(object state, bool timedOut);
type WaitOrTimerCallback = delegate of obj * bool -> unit
Public Delegate Sub WaitOrTimerCallback(state As Object, timedOut As Boolean)

Paramètres

state
Object

Objet contenant les informations que la méthode de rappel doit utiliser à chacune de ses exécutions.An object containing information to be used by the callback method each time it executes.

timedOut
Boolean

true si le WaitHandle a expiré ; false s'il a été signalé.true if the WaitHandle timed out; false if it was signaled.

Héritage
WaitOrTimerCallback
Attributs

Exemples

L’exemple suivant montre comment utiliser le WaitOrTimerCallback délégué pour représenter une méthode de rappel qui est exécutée lorsqu’un handle d’attente est signalé.The following example shows how to use the WaitOrTimerCallback delegate to represent a callback method that is executed when a wait handle is signaled.

L’exemple montre également comment utiliser la RegisterWaitForSingleObject méthode pour exécuter une méthode de rappel spécifiée lorsqu’un handle d’attente spécifié est signalé.The example also shows how to use the RegisterWaitForSingleObject method to execute a specified callback method when a specified wait handle is signaled. Dans cet exemple, la méthode de rappel WaitProc est et le handle d’attente AutoResetEventest un.In this example, the callback method is WaitProc and the wait handle is an AutoResetEvent.

L’exemple définit une TaskInfo classe pour contenir les informations passées au rappel lorsqu’il s’exécute.The example defines a TaskInfo class to hold the information that is passed to the callback when it executes. L’exemple crée un TaskInfo objet et lui assigne des données de chaîne.The example creates a TaskInfo object and assigns it some string data. La RegisteredWaitHandle qui est retournée par RegisterWaitForSingleObject la Handle méthode est assignée au champ TaskInfo de l' RegisteredWaitHandleobjet, afin que la méthode de rappel ait accès au.The RegisteredWaitHandle that is returned by the RegisterWaitForSingleObject method is assigned to the Handle field of the TaskInfo object, so that the callback method has access to the RegisteredWaitHandle.

En plus de l' TaskInfo objet, l’appel à la RegisterWaitForSingleObject méthode spécifie AutoResetEvent le délai d’attente de la tâche WaitOrTimerCallback , un délégué qui WaitProc représente la méthode de rappel, un intervalle de délai d’attente d’une seconde et plusieurs rappels. .In addition to the TaskInfo object, the call to the RegisterWaitForSingleObject method specifies the AutoResetEvent the task waits on, a WaitOrTimerCallback delegate that represents the WaitProc callback method, a one-second timeout interval, and multiple callbacks.

Lorsque le thread principal signale AutoResetEvent le en appelant Set sa méthode, WaitOrTimerCallback le délégué est appelé.When the main thread signals the AutoResetEvent by calling its Set method, the WaitOrTimerCallback delegate is invoked. La WaitProc méthode effectue RegisteredWaitHandle un test pour déterminer si un délai d’attente a été dépassé.The WaitProc method tests RegisteredWaitHandle to determine whether a timeout occurred. Si le rappel a été appelé parce que le handle d’attente a été signalé WaitProc , la méthode annule RegisteredWaitHandlel’inscription du, en arrêtant les rappels supplémentaires.If the callback was invoked because the wait handle was signaled, the WaitProc method unregisters the RegisteredWaitHandle, stopping further callbacks. Dans le cas d’un délai d’attente, la tâche continue à attendre.In the case of a timeout, the task continues waiting. La WaitProc méthode se termine en imprimant un message sur la console.The WaitProc method ends by printing a message to the 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

Remarques

WaitOrTimerCallbackreprésente une méthode de rappel que vous souhaitez exécuter lorsqu’un handle d’attente inscrit expire ou est signalé.WaitOrTimerCallback represents a callback method that you want to execute when a registered wait handle times out or is signaled. Créez le délégué en passant votre méthode de rappel au WaitOrTimerCallback constructeur.Create the delegate by passing your callback method to the WaitOrTimerCallback constructor. Votre méthode doit avoir la signature indiquée ici.Your method must have the signature shown here.

Créez le handle d’attente inscrit en passant WaitOrTimerCallback le délégué et WaitHandle un ThreadPool.RegisterWaitForSingleObjectà.Create the registered wait handle by passing the WaitOrTimerCallback delegate and a WaitHandle to ThreadPool.RegisterWaitForSingleObject. Votre méthode de rappel s’exécute chaque fois WaitHandle que le expire ou est signalé.Your callback method executes each time the WaitHandle times out or is signaled.

Notes

Visual Basic utilisateurs peuvent omettre le WaitOrTimerCallback constructeur et simplement utiliser l' AddressOf opérateur lors du passage de la méthode de RegisterWaitForSingleObjectrappel à.Visual Basic users can omit the WaitOrTimerCallback constructor, and simply use the AddressOf operator when passing the callback method to RegisterWaitForSingleObject. Visual Basic appelle automatiquement le constructeur délégué approprié.Visual Basic automatically calls the correct delegate constructor.

Si vous souhaitez passer des informations à votre méthode de rappel, créez un objet qui contient les informations nécessaires et transmettez RegisterWaitForSingleObject -le à lorsque vous créez le handle d’attente inscrit.If you want to pass information to your callback method, create an object that contains the necessary information and pass it to RegisterWaitForSingleObject when you create the registered wait handle. Chaque fois que votre méthode de rappel s’exécute state , le paramètre contient cet objet.Each time your callback method executes, the state parameter contains this object.

Pour plus d’informations sur l’utilisation des méthodes de rappel pour synchroniser des threads de pool de threads, consultez pool de threads managés.For more information about using callback methods to synchronize thread pool threads, see The managed thread pool.

Méthodes d’extension

GetMethodInfo(Delegate)

Obtient un objet qui représente la méthode représentée par le délégué spécifié.Gets an object that represents the method represented by the specified delegate.

S’applique à

Voir aussi