Thread.Sleep() is evil

Introduction

Thread.Sleep(n>0) can be used to perform tests or debugging operations in some scenarios. I don’t see a good reason for its use in production code.

Any waiting thread can be a huge waste of resources. By default, a thread reserves 1 megabyte of virtual memory for its stack and a few more CPU cycles on each context switch.

First example

Look at this code on listing 1 taken from stackoverflow:

Listing 1. Problems with using Thread.Sleep for short times.

Thread.Sleep(n>0) will block the current thread for the number of timeslices that can occur within n milliseconds. The length of a timeslice may be different depending on the version/type of Windows and the processor, usually ranging from 15 to 30 milliseconds. Therefore, it’s almost impossible for your thread to be blocked for the precisely specified millisecond interval if it’s less than 15 milliseconds.

Second example

Did you see what I said on my tweet?

Let me explain a bit better. Take a look on this code from listing 2 below:

Listing 2. Forgotten thread.

If you run this program from the command line, as shown in Listing 3.

Listing 3. Running ThreadSleepTest program from cmd on Windows.

The contents of the generated text file will be:

“On the main thread id n
Closing…
Now on thread n doing some work…”

As you can see finally blocks in background threads are not executed when the process terminates because the main thread has finished its execution. If you need things like releasing resources, closing streams, deleting some temporary files or things like that, so that’s when you don’t make good use of Thread.Sleep(n>0) since you’re not aware of what might happen even being as obvious as this may seem.

Thread.Sleep( 0 ) is even worse

And using Thread.Sleep(0) is even worse because it can affect the responsiveness of the entire system in the way it schedule tasks, threads and processes if you are using Thread.Sleep(0) many times.

Conclusion

At last, Thread.Sleep() is evil and maybe it can be avoided with a Timer in the production code. There are other solutions for large-scale projects, but this subject is outside the scope of the purpose of this post. You shouldn’t try to solve everything just with code.

I hope that if you think about using Thread.Sleep() again, from now on you are more aware of the side effects it may produce.

Thank you for your time reading this!

 

Last edited on Mar, 27, 2019 at 9:36 pm