Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.Sleep(-1)

What is the use of

 System.Threading.Thread.Sleep(-1)

I would expect this to throw an exception, as the documentation for Thread.Sleep says this

The value of timeout is negative and is not equal to Timeout.Infinite in milliseconds, or is greater than Int32.MaxValue milliseconds.

However, the above Thread.Sleep(-1) doesn't throw an exception. When I look at ReferenceSource I see

[System.Security.SecuritySafeCritical]  // auto-generated
public static void Sleep(int millisecondsTimeout)
{
    SleepInternal(millisecondsTimeout);
    // Ensure we don't return to app code when the pause is underway
    if(AppDomainPauseManager.IsPaused)
        AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
}

public static void Sleep(TimeSpan timeout)
{
    long tm = (long)timeout.TotalMilliseconds;
    if (tm < -1 || tm > (long) Int32.MaxValue)
        throw new  ArgumentOutOfRangeException("timeout",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
    Sleep((int)tm);
}

Which looks like it doesn't throw for a negative timespan, but only a negative timespan less than -1.

And indeed

 Thread.Sleep(-2);

Does indeed crash.

So what is the special case here of -1. What is Thread.Sleep(-1) actually doing?

like image 768
Stuart Avatar asked May 10 '18 09:05

Stuart


2 Answers

The value of Timeout.Infinite == -1.

Timeout.Infinite : A constant used to specify an infinite waiting period, for threading methods that accept an Int32 parameter.

like image 196
spender Avatar answered Oct 19 '22 23:10

spender


This is a special case that essentially means "sleep until someone prods you" - which another thread can do by calling Thread.Interrupt(). The sleeping thread should then expect to catch a ThreadInterruptedException.

like image 7
Marc Gravell Avatar answered Oct 19 '22 23:10

Marc Gravell