More specifically, does the performance degradation of context switching apply to threads that are in a wait state?
Under what conditions or circumstances would a ManualResetEvent, or WaitHandle, be likely to consume resources?
A ManualResetEvent doesn't have a wait state. The only thing that can wait on an MRE is a thread. And yes, a thread consumes plenty of precious resources needlessly when it is not doing what it was made to do, execute code. A megabyte of virtual memory and a handful of kernel objects. The single kernel object that MRE consumes is small potatoes compared to that.
You typically want to use a threadpool thread instead.
And look at what's available in .NET 4.0. Like ManualResetEventSlim (not based on an OS object) and the Task class.
In the case of a ManualResetEvent, no. The thread isn't actually looping, or anything. It's just got a reference to itself stuffed into the ManualResetEvent's notification list. When ANOTHER thread calls .Set on the ManualResetEvent, that other thread ends up putting the waiting thread back into the active queue.
The resources consumed are simply the accounting for the existence of the thread: the stack, whatever kernel resources are recorded, saved registers, etc. Now, if the thread you were speaking of wasn't using a ManualResetEvent, but instead a wait-loop of some sort, then sure.
Now, WaitHandle isn't an implementation. It's the just abstract API. There's no telling how other implementations of WaitHandle might work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With