IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

Forget 42, –1 is My New Answer to Life

I’ve just stumbled upon the next code statement – Thread.Sleep(-1). It left me wondering what was happening there since MSDN tells you nothing about a –1 value for the milliseconds parameter:

“The number of milliseconds for which the thread is blocked. Specify zero (0) to indicate that this thread should be suspended to allow other waiting threads to execute. Specify Infinite to block the thread indefinitely.“ – System.Threading.Thread.Sleep, MSDN

To check that out, I opened the IronRuby interactive console and filled in System::Threading::Thread.Sleep(-1) and hit Enter just to find out that this call blocks the thread indefinitely. Could it be? –1 is Infinite?

Reflector to our aid! oh wait, RedGate now charges money for it and had planted a time bomb inside the free version which made it stop working. grrrr
ILSpy to our aid! (I highly recommend ILSpy as a Reflector alternative… very similar, free, oss… great community effort!)

Anyway, ILSpy proved my concerns:

System.Threading.Timeout.Infinite Value

So… –1 actually represents Infinity (when it comes to threading in .NET). And Infinity is much cooler than 42, hence –1 is the new answer to life.
Q.E.D.

All the best,
Shay.



Comments (4) -

Germany Falko Janak

Hello Shay,
nice hint. Can you give an example when to block a thread indefinitely?
Thx,
Falko

Reply

I ran into this particular code statement in Microsoft's implementation of the RoleEntryPoint class (the base class for Azure roles). In general, you'd want to use it when you're doing operations not on the main thread and you want your application to remain active.

Reply

What do you mean by time bomb in the free version of Redgate? Does ILSpy provide all the functionalities that Redgate provides.?

Reply

This came from the INFINITE definition in Win32 which is the unsigned value 0xFFFFFFFF == -1.

Alon

Reply

Add comment