views:

261

answers:

1

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'.

+1  A: 

None is better. A timer is used to periodically "poke" your thread to do something. WaitForSingleObject waits on handles. The timeout is there so you can use it to decide to stop waiting instead of being stuck in deadlock. Using a timer to break the waitforsingleobject out of a lock is not required if you use the timeout.

The resource cost is negligible for both. I cant say which approach you should use because its highly dependent on the code situation you have.

Andrew Keith
I don't agree. It's a straightforward question: cost of allocating a timer vs cost of allocating a waithandle and a WaitForSingleObject. They are both OS resources. One must cost more than the other, irrespective of my situation.And whilst in this scenario I am talking about a 'one off' timer, *both* can be used to periodically 'poke' your code - you can use the 'executeOnlyOnce' flag on RegisterWaitForSingleObject...
piers7