Lunyx Lunyx - 1 month ago 13
C# Question

Is Thread.Sleep(Timeout.Infinite); more efficient than while(true){}?

I have a console application that I would like to keep open all of the time while still listening in to events. I have tested

Thread.Sleep(Timeout.Infinite);
and
while (true) { }
and both allow the events to be raised while keeping the console application open. Is there one that I should be using over the other? If the thread is sleeping, is there anything that I should not be doing, such as modifying a static collection declared in the scope of the class?

Answer

I would recommend using a ManualResetEvent (or other WaitHandle), and calling ManualResetEvent.WaitOne.

This will have a similar effect to sleeping forever, except that it provides you a clean way to exit from your infinite "block" when desired (by calling Set() on the event).

Using while(true) will consume CPU cycles, so it's definitely something to avoid.

is there anything that I should not be doing, such as modifying a static collection declared in the scope of the class?

In general, no. Since your thread will be blocked, there shouldn't be any synchronization issues with using shared data (provided the items within the collection don't have specific requirements, such as user interface elements which must be used on a thread with a proper synchronization context.)