Using The ThreadPool Class - 2
We cal also queue work items that have wait operations involved with them to the thread pool. The method is defined as such:
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object state,
int millisecondsTimeOutInterval,
bool executeOnlyOnce);
Example:
class RegWait
{
private static int i = 0;
public static void Main()
{
AutoResetEvent
arev = new AutoResetEvent(false);
ThreadPool.RegisterWaitForSingleObject(arev, new WaitOrTimerCallback(WorkItem), null, 2000, true);
Thread.Sleep(3000);
arev.Set();
Console.ReadKey(false);
}
public static void WorkItem(object o, bool timedOut)
{}
Console.WriteLine("Thread Pool Work Item Invoked: " + i++ + "
timedOut = " + timedOut);
while (true){}
Console.WriteLine("Hello hello");
}
WaitHandle waitObject
RegisterWaitForSingleObject() takes in a wait handle, for this example we pass it an AutoResetEvent object.
WaitOrTimerCallback callBack
Its second argument is a delegate for WaitOrTimerCallback which has the signature of
public delegate void WaitOrTimerCallback( object state, bool timedOut );
timeOut is true if the WaitHandle timed out; false if it was signaled.
object state
The third argument is the object to be passed to the thread.
int millisecondsTimeOutInterval
This is the amount of time to wait for WaitHandle (amount of time to wait if the current WaitHandle is not signaled) before the WaitOrTimerCallback delegate is called.
bool executeOnlyOnce
True if the WaitOrTimerCallback delegate is executed only once.
False if the WaitOrTimerCallback delegate keeps executing whenever the millisecondsTimeOutInterval expires.
Usage:
The RegisterWaitForSingleObject queues the delegate to the thread pool. The worker thread will only execute the delegate if these two events occur:
(1) The WaitHandle is in the signaled state.The RegisterWaitForSingleObject method checks the current state of the specified object's WaitHandle. If the object's state is unsignaled, the method registers a wait operation. The wait operation is performed by a thread from the thread pool. The delegate is executed by a worker thread when the object's state becomes signaled or the time-out interval elapses. If the timeOutInterval parameter is not zero (0) and the executeOnlyOnce parameter is false, the timer is reset every time the event is signaled or the time-out interval elapses.
(2) The time-out interval elapses
To cancel the wait operation, call the RegisteredWaitHandle.Unregister method - public bool Unregister(WaitHandle waitObject); [It returns true if the function succeed or false if otherwise) For example:
RegisteredWaitHandle wHandle = ThreadPool.RegisterWaitForSingleObject(
arev, new WaitOrTimerCallback(WorkItem), null, 500, false);
To cancel the wait operation, call wHandle.Unregister(arev)