净超时:WaitForSingleObject的VS定时器 [英] .Net Timeouts: WaitForSingleObject vs Timer
问题描述
我实施的异步操作(一系列网络IO的)超时,我不知道这是'好'(从分配/性能)的角度来看:在创建的EventWaitHandle和使用RegisterWaitForSingleObject,或者只是创建一个计时器并使用它的蜱。
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.
在我的特定情况下的EventWaitHandle是懒惰创建的,但显然它不得不被实例化使用WaitForSingleObject的。因此,其实这是一个关于的WaitHandle +的WaitForSingleObject的VS一个定时器资源成本的问题。这两种方法都一样容易实现。
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'.
推荐答案
微软摩根斯金纳的似乎preFER RegisterWaitForSingleObject 。
至于分配而言,反射显示, RegisterWaitForSingleObject
创建实例的 RegisteredWaitHandle
,而计时器创建一个内部 TimerBase
,以及一类名为 _TimerCallback
。人们可以继续下去,并比较这些类等的尺寸,但他们似乎有更多的相关性,尤其是那些非托管(包括使用底层的Win32函数) - 所以我真的不能给出一个明确的答案。
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.
至于传递给 RegisterWaitForSingleObject
等待句柄但是,请记住,你可以分配一个Maunal /的AutoResetEvent,并传递给所有的呼叫(因为你指望超时,所以你从来没有信号也无妨)。
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).
至于性能也越高,我也不清楚。线程池将使用一种特殊的等待线程通过 RegisterWaitForSingleObject
注册的每个63的动作。与此相反,一个计时器将使用一个基础Win32定时器。双方最终将使用一个线程池的工作线程的实际执行。这是在该情况下更好?击败我。所以我用斯金纳在这一个地方:)
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 :)
另请参见:
- 多线程:注册等待的
- <一个href="http://msmvps.com/blogs/luisabreu/archive/2009/06/03/multithreading-coding-the-register-wait-pattern.aspx"相对=nofollow>多线程:编码登记等待模式
- Multithreading: registered waits
- Multithreading: coding the register wait pattern
这篇关于净超时:WaitForSingleObject的VS定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!