CodeSOD: I Feel Asleep
When your program needs to pause, there are several options. The first is a pure busy loop- usually a bad idea, but frequently more efficient for very short delays than other options. The "standard" is to sleep your program- just tell the OS scheduler to let other programs run and to wake you up after some interval. In multithreaded programs, you'll frequently sleep one thread while waiting on others.
Which is what Cisco's co-worker sort of did. Sort of.
float TimeLeftSec;//...private void ContinueSleep(Action action){ for (TimeLeftSec -= 0.1f; TimeLeftSec > 0; ) { Task.Factory.StartNew(() => { Thread.Sleep(100); ContinueSleep(action); }); return; } action();}
I think the intent is a little clearer than the code is. The goal is to execute an Action after TimeLeftSec has expired. We do this by decrementing TimeLeftSec by 100ms, starting a new thread that sleeps for 100ms, and then we attempt to perform the action again.
That core algorithm is already pretty bonkers. Why not just sleep for TimeLeftSec and make this easy?
But the implementation adds extra layers to it. Like TimeLeftSec which is a global variable that's getting modified inside of a thread. Or the for and return which are basically pretending to be an if statement.
"Needless to say," Cisco adds, the developer responsible "only lasted one year at the company."
Only? One year seems like a lot, if it leads to code like this. The person who could fire them must have been ContinueSleeping.
[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!