Appreciating the System ThreadPool - ' Wait Callbacks ' (
Page 4 of 4 )
Wait Callbacks
Many tasks that take significant clock time actually take comparatively little
CPU time, because they spend most of their time blocked, waiting for an OS wait
handle. They may be waiting for network activity, file IO, a timer, or whatever.
As an alternative to creating a thread that spends a lot of time blocked,
waiting for one event or another, you can use ThreadPool. RegisterWaitForSingleObject to register an OS wait handle and a WaitOrTimerCallback delegate
that gets called when the handle is signaled. The ThreadPool uses
OS functions that block a single thread until any of several wait handles is
signaled. This thread determines which wait handle signaled, then calls the
associated delegate in a worker thread.
This not only avoids thread creation overhead but also reduces the number of
blocked threads. For example, it may be easier, clearer, and safer to implement
a network protocol as a thread which blocks at each step of the protocol; but it
may be more efficient to implement the protocol as a web of delegates called as
each handle is signaled, most of which fire off some response and then register
another delegate and another wait. (The safest way to create such a web is
probably to compile some sort of blocking script.)
Each wait can timeout or the wait can be infinite; the WaitOrTimerCallback
delegate takes a parameter that tells the delegate whether it is being called
because the handle was signaled or because the wait timed out.
Registering a wait with the ThreadPool is perhaps most appropriate
where the event will keep being signaled, and you want to do the same thing each
time. (You may be monitoring some sort of news feed, for example, or trading
messages with another process.) Each call to ThreadPool.RegisterWaitForSingleObject
includes an executeOnlyOnce parameter; when the Only Once
parameter is false, the ThreadPool will keep waiting
for the registered event until you call Unregister on the RegisteredWaitHandle
you get from RegisterWaitForSingleObject.
Jon Shemitz is a consultant and an author. You may contact him at www.midnightbeach.com. This article will appear, in different form, in his forthcoming book, .NET 2.0 For Delphi Programmers (Apress, June 2006).