.Net Timeouts: WaitForSingleObject vs Timer

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 RegisterWaitForSingleObject create an instance of a RegisteredWaitHandle , while a timer creates an internal TimerBase , 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 RegisterWaitForSingleObject though, 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:

  • Multithreading: registered waits
  • Multithreading: coding the register wait pattern

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

    链接地址: http://www.djcxy.com/p/43504.html

    上一篇: 稀疏结帐和svn:外部

    下一篇: .Net超时:WaitForSingleObject vs Timer