WaitOrTimerCallback WaitOrTimerCallback WaitOrTimerCallback WaitOrTimerCallback Delegate

Definizione

Rappresenta un metodo da chiamare quando WaitHandle riceve un segnale o esegue il timeout.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)

Parametri

state
Object Object Object Object

Oggetto contenente informazioni che devono essere utilizzate dal metodo di callback ogni volta che viene eseguito.An object containing information to be used by the callback method each time it executes.

timedOut
Boolean Boolean Boolean Boolean

Il valore è true se WaitHandle ha eseguito il timeout; è false se ha ricevuto un segnale.true if the WaitHandle timed out; false if it was signaled.

Ereditarietà
WaitOrTimerCallbackWaitOrTimerCallbackWaitOrTimerCallbackWaitOrTimerCallback
Attributi

Esempi

Nell'esempio seguente viene illustrato come utilizzare il WaitOrTimerCallback delegato per rappresentare un metodo di callback eseguito quando viene segnalato un handle di attesa.The following example shows how to use the WaitOrTimerCallback delegate to represent a callback method that is executed when a wait handle is signaled.

Nell'esempio viene inoltre illustrato come utilizzare il RegisterWaitForSingleObject metodo per eseguire un metodo di callback specificato quando viene segnalato un handle di attesa specificato.The example also shows how to use the RegisterWaitForSingleObject method to execute a specified callback method when a specified wait handle is signaled. In questo esempio, il metodo di callback WaitProc è e l'handle di attesa AutoResetEventè un.In this example, the callback method is WaitProc and the wait handle is an AutoResetEvent.

Nell'esempio viene definita TaskInfo una classe che conterrà le informazioni che vengono passate al callback quando viene eseguita.The example defines a TaskInfo class to hold the information that is passed to the callback when it executes. Nell'esempio viene creato TaskInfo un oggetto a cui vengono assegnati alcuni dati di stringa.The example creates a TaskInfo object and assigns it some string data. L' RegisteredWaitHandle RegisterWaitForSingleObject oggettorestituitoHandle dal metodo viene assegnato alcampodell'oggetto,inmodocheilmetododicallbackabbiaaccessoa.RegisteredWaitHandle TaskInfoThe 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.

Oltre TaskInfo all'oggetto, la chiamata RegisterWaitForSingleObject al metodo specifica il AutoResetEvent tempo di attesa dell'attività, un WaitOrTimerCallback delegato che rappresenta il WaitProc metodo di callback, un intervallo di timeout di un secondo e più callback .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.

Quando il thread principale segnala AutoResetEvent a chiamando il relativo Set metodo, viene richiamato il WaitOrTimerCallback delegato.When the main thread signals the AutoResetEvent by calling its Set method, the WaitOrTimerCallback delegate is invoked. Il WaitProc metodo verifica RegisteredWaitHandle per determinare se si è verificato un timeout.The WaitProc method tests RegisteredWaitHandle to determine whether a timeout occurred. Se il callback è stato richiamato perché l'handle di attesa è stato WaitProc segnalato, il metodo Annulla RegisteredWaitHandlela registrazione dell'oggetto, arrestando ulteriori callback.If the callback was invoked because the wait handle was signaled, the WaitProc method unregisters the RegisteredWaitHandle, stopping further callbacks. In caso di timeout, l'attività rimane in attesa.In the case of a timeout, the task continues waiting. Il WaitProc metodo termina stampando un messaggio nella 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

Commenti

WaitOrTimerCallbackrappresenta un metodo di callback che si desidera eseguire quando un handle di attesa registrato scade o viene segnalato.WaitOrTimerCallback represents a callback method that you want to execute when a registered wait handle times out or is signaled. Creare il delegato passando il metodo di callback al WaitOrTimerCallback costruttore.Create the delegate by passing your callback method to the WaitOrTimerCallback constructor. Il metodo deve avere la firma riportata qui.Your method must have the signature shown here.

Creare l'handle di attesa registrato passando il WaitOrTimerCallback delegato e un WaitHandle a ThreadPool.RegisterWaitForSingleObject.Create the registered wait handle by passing the WaitOrTimerCallback delegate and a WaitHandle to ThreadPool.RegisterWaitForSingleObject. Il metodo di callback viene eseguito ogni volta WaitHandle che il timeout o viene segnalato.Your callback method executes each time the WaitHandle times out or is signaled.

Nota

Visual Basic gli utenti possono omettere il WaitOrTimerCallback costruttore e usare semplicemente l' AddressOf operatore quando passano il metodo di RegisterWaitForSingleObjectcallback a.Visual Basic users can omit the WaitOrTimerCallback constructor, and simply use the AddressOf operator when passing the callback method to RegisterWaitForSingleObject. Visual Basic chiama automaticamente il costruttore di delegato corretto.Visual Basic automatically calls the correct delegate constructor.

Se si desidera passare informazioni al metodo di callback, creare un oggetto contenente le informazioni necessarie e passarlo a RegisterWaitForSingleObject quando si crea l'handle di attesa registrato.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. Ogni volta che viene eseguito il metodo di callback state , il parametro contiene questo oggetto.Each time your callback method executes, the state parameter contains this object.

Per ulteriori informazioni sull'utilizzo dei metodi di callback per sincronizzare i thread del pool di thread, vedere il pool di thread gestiti.For more information about using callback methods to synchronize thread pool threads, see The managed thread pool.

Metodi di estensione

GetMethodInfo(Delegate) GetMethodInfo(Delegate) GetMethodInfo(Delegate) GetMethodInfo(Delegate)

Ottiene un oggetto che rappresenta il metodo rappresentato dal delegato specificato.Gets an object that represents the method represented by the specified delegate.

Si applica a

Vedi anche