I’m implementing a timeout on an asynchronous operation (a series of network IOs), and I’m not sure which is ‘better’ (from a allocations / performance) perspective: creating an EventWaitHandle and using RegisterWaitForSingleObject, or just creating a Timer and using its Tick.
In my specific case the EventWaitHandle is lazy-created, but obviously it’d have to be instantiated to use WaitForSingleObject. So really this is a question about the resource cost of a WaitHandle + WaitForSingleObject vs a Timer. Both approaches are about as easy to implement.
I’ve implemented both at various times, so I understand the terrain, I’m just not sure which approach is ‘better’.
Microsoft’s Morgan Skinner seems to prefer RegisterWaitForSingleObject.
As far as allocations are concerned, reflector reveals that
RegisterWaitForSingleObjectcreate an instance of aRegisteredWaitHandle, while a timer creates an internalTimerBase, as well as a class named_TimerCallback. One could go on and compare the sizes of these classes and so forth, but they seem to be have more dependencies, especially unmanaged ones (both use underlying win32 functions) – so I really can’t give a straight answer.Regarding the wait handle passed to
RegisterWaitForSingleObjectthough, Keep in mind that you could allocate a single Maunal/AutoResetEvent and pass that to all calls (since you’re counting on the timeout, so you’d never signal it anyway).As far as performance goes, I’m not sure either. The ThreadPool will use a special waiting thread for each 63 actions registered via
RegisterWaitForSingleObject. In contrast, a timer will use an underlying win32 timer. Both will end up using a ThreadPool worker thread for the actual execution. Which is better in which scenarios ? Beats me.. so I’d go with Skinner on this one 🙂Also see: