首页 > 解决方案 > 线程.睡眠(-1)

问题描述

有什么用

 System.Threading.Thread.Sleep(-1)

我希望这会引发异常,因为 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);
}

看起来它不会抛出负时间跨度,而只会抛出小于 -1 的负时间跨度。

确实

 Thread.Sleep(-2);

确实会崩溃。

那么这里的特殊情况是什么-1Thread.Sleep(-1)实际在做什么?

标签: c#multithreading

解决方案


Timeout.Infinite== -1的值。

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


推荐阅读