I sometimes encounter code in the following form:
while (true) {
//do something
Thread.Sleep(1000);
}
I was wondering if this is considered
An alternative approach may be using an AutoResetEvent
and instantiate it signaled by default.
public class Program
{
public static readonly AutoResetEvent ResetEvent = new AutoResetEvent(true);
public static void Main(string[] args)
{
Task.Factory.StartNew
(
() =>
{
// Imagine sleep is a long task which ends in 10 seconds
Thread.Sleep(10000);
// We release the whole AutoResetEvent
ResetEvent.Set();
}
);
// Once other thread sets the AutoResetEvent, the program ends
ResetEvent.WaitOne();
}
}
while(true)
a bad practice?Well, in fact, a literal true as while
loop condition may be considered a bad practice, since it's an unbrekeable loop: I would always use a variable condition which may result in true
or false
.
while
loop or something like the AutoResetEvent
approach?while
loop......when you need to execute code while waiting the program to end.
AutoResetEvent
approach......when you just need to hold the main thread in order to prevent the program to end, but such main thread just needs to wait until some other thread requests a program exit.