I’ve read on RegisterWaitForSingleObject in:
http://www.albahari.com
And I don’t understand when would I prefer to use AutoResetEvent and not RegisterWaitForSingleObject?
It seems that we can always use RegisterWaitForSingleObject, and its better than AutoResetEvent since its not tied to thread.
You are comparing an apple and an orange. RWFSO needs a wait handle. Like an AutoResetEvent. What RWFSO does is optimize the waiting for the event. Without it, you’ll need to call the event’s WaitXxx() method.
Caling WaitOne() blocks the thread until the event is Set(). This is something you want to avoid in a threadpool thread because blocked TP threads prevent other scheduled TP threads from executing quickly. The threadpool manager tries the optimize the number of running TP threads so there are no more executing TP threads than cpu cores. A blocking thread kinda screws that up, the manager isn’t otherwise smart enough to know why a thread is blocking. Only when blocking TP threads don’t make progress for half a second does the manager allow another waiting TP thread to execute.
RWFSO is quite nice but certainly not always appropriate. Programming with it is fairly awkward, especially when you want to handle exceptions. There’s a nasty implicit race if you ever need to cancel it. The TP thread that runs when the event is signaled is subject to the same kind of TP scheduling delays. And there is no RegisterWaitForMultipleObjects(), threading often requires using WaitAny(). Intuitively: on one event that tells the thread something is ready, another event that tells the thread to exit.