WaitOrTimerCallback 委托

定义

表示当 WaitHandle 超时或终止时要调用的方法。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)

参数

state
Object

一个对象,包含回调方法在每次执行时要使用的信息。An object containing information to be used by the callback method each time it executes.

timedOut
Boolean

如果 WaitHandle 超时,则为 true;如果其终止,则为 falsetrue if the WaitHandle timed out; false if it was signaled.

继承
WaitOrTimerCallback
属性

示例

下面的示例演示如何使用WaitOrTimerCallback委托表示在等待句柄终止时执行的回调方法。The following example shows how to use the WaitOrTimerCallback delegate to represent a callback method that is executed when a wait handle is signaled.

该示例还演示了如何使用RegisterWaitForSingleObject方法在指定的等待句柄收到信号时执行指定的回调方法。The example also shows how to use the RegisterWaitForSingleObject method to execute a specified callback method when a specified wait handle is signaled. 在此示例中, 回调方法为WaitProc , 等待句柄AutoResetEvent是。In this example, the callback method is WaitProc and the wait handle is an AutoResetEvent.

该示例定义了TaskInfo一个类, 用于保存在执行时传递给回调的信息。The example defines a TaskInfo class to hold the information that is passed to the callback when it executes. 该示例创建一个TaskInfo对象, 并为其分配一些字符串数据。The example creates a TaskInfo object and assigns it some string data. RegisteredWaitHandle 方法返回的将TaskInfo分配给对象的字段,以便回调方法有权访问。RegisteredWaitHandle Handle RegisterWaitForSingleObjectThe 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.

除了TaskInfo对象之外, 对RegisterWaitForSingleObject方法的调用还指定AutoResetEvent了任务WaitProc等待、 WaitOrTimerCallback表示回调方法的委托、一秒的超时间隔和多个回调.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.

当主线程AutoResetEvent通过调用其Set方法发出信号时, WaitOrTimerCallback将调用委托。When the main thread signals the AutoResetEvent by calling its Set method, the WaitOrTimerCallback delegate is invoked. WaitProc方法测试RegisteredWaitHandle以确定是否发生了超时。The WaitProc method tests RegisteredWaitHandle to determine whether a timeout occurred. 如果回调是由于等待句柄已发出信号而调用的WaitProc , 则该RegisteredWaitHandle方法将取消注册, 从而停止进一步的回调。If the callback was invoked because the wait handle was signaled, the WaitProc method unregisters the RegisteredWaitHandle, stopping further callbacks. 在超时情况下, 任务将继续等待。In the case of a timeout, the task continues waiting. WaitProc方法通过将消息打印到控制台来结束。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

注解

WaitOrTimerCallback表示一个回调方法, 当注册的等待句柄超时或终止时, 您希望执行此方法。WaitOrTimerCallback represents a callback method that you want to execute when a registered wait handle times out or is signaled. 通过向WaitOrTimerCallback构造函数传递回调方法来创建委托。Create the delegate by passing your callback method to the WaitOrTimerCallback constructor. 你的方法必须具有此处显示的签名。Your method must have the signature shown here.

通过WaitOrTimerCallback WaitHandle将委托和传递到来ThreadPool.RegisterWaitForSingleObject创建已注册的等待句柄。Create the registered wait handle by passing the WaitOrTimerCallback delegate and a WaitHandle to ThreadPool.RegisterWaitForSingleObject. 每次WaitHandle超时时或终止时, 您的回调方法都将执行。Your callback method executes each time the WaitHandle times out or is signaled.

备注

Visual Basic 用户可以省略WaitOrTimerCallback构造函数, 并且只需在将回调方法传递给RegisterWaitForSingleObjectAddressOf使用运算符。Visual Basic users can omit the WaitOrTimerCallback constructor, and simply use the AddressOf operator when passing the callback method to RegisterWaitForSingleObject. Visual Basic 自动调用正确的委托构造函数。Visual Basic automatically calls the correct delegate constructor.

如果要将信息传递到回调方法, 请创建一个包含所需信息的对象, 并在创建已RegisterWaitForSingleObject注册的等待句柄时将其传递到。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. 每次执行回调方法时, state参数都包含此对象。Each time your callback method executes, the state parameter contains this object.

有关使用回调方法同步线程池线程的详细信息, 请参阅托管线程池For more information about using callback methods to synchronize thread pool threads, see The managed thread pool.

扩展方法

GetMethodInfo(Delegate)

获取指示指定委托表示的方法的对象。Gets an object that represents the method represented by the specified delegate.

适用于

另请参阅