Thread.sleep代码(-1)

Stu*_*art 5 c# multithreading

有什么用?

 System.Threading.Thread.Sleep(-1)
Run Code Online (Sandbox Code Playgroud)

我希望这会引发异常,因为Thread.Sleep的文档说明了这一点

timeout的值为负,不等于Timeout.Infinite(以毫秒为单位),或者大于Int32.MaxValue毫秒.

但是,上面的Thread.Sleep(-1)不会抛出异常.当我看到ReferenceSource时,我看到了

[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);
}
Run Code Online (Sandbox Code Playgroud)

看起来它不会在负时间范围内抛出,但只有负时间跨度小于-1.

确实如此

 Thread.Sleep(-2);
Run Code Online (Sandbox Code Playgroud)

确实会崩溃.

那么这里的特例是什么呢-1?什么是Thread.Sleep(-1)真正在做什么?

spe*_*der 10

Timeout.Infinite== -1.

Timeout.Infinite :用于为接受Int32参数的线程方法指定无限等待时间的常量.


Mar*_*ell 6

这是一个特殊情况,本质上意味着"睡到有人刺激你" - 另一个线程可以通过调用来做Thread.Interrupt().然后睡眠的线程应该期待捕获ThreadInterruptedException.