Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the ManualResetEvent consume cpu while it is in a wait state?

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?

like image 413
Eric Dahlvang Avatar asked Feb 22 '23 10:02

Eric Dahlvang


2 Answers

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.

like image 170
Hans Passant Avatar answered Feb 24 '23 00:02

Hans Passant


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.

like image 43
Jerome Haltom Avatar answered Feb 23 '23 22:02

Jerome Haltom