c# - 线程.睡眠(-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 参数的线程方法。
推荐阅读
- javascript - style.display="none" 在 else{} 中有效,但在 if{} 中无效
- javascript - 长数组组类别中的 Highchart
- javascript - Promise.all 在带有 FP 承诺的对象数组上
- arduino-uno - 三轮机器人不使用语音命令向后或向左移动
- javascript - Javascript 混淆和模态框
- dhis-2 - DHIS2-live 在 Windows 中无法正常工作
- mysql - MySQL LEFT JOIN 与 GROUP BY 和聚合运算符阻塞
- node.js - Node.js 使用 Promise.all 来返回异步调用?
- ios - 如何获取 iOS 应用程序,以便我可以通过 whatsapp 或任何其他信使共享它
- c# - 有没有办法结合foreach循环