繁体   English   中英

Thread.sleep代码(-1)

[英]Thread.Sleep(-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);

确实会崩溃。

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

Timeout.Infinite的值== -1。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM