You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Thread.Sleep(-1)为何不抛异常?其实际作用是什么?

Understanding Thread.Sleep(-1) Behavior and Edge Cases

Great question—this is a classic example of how implementation details and documentation can have subtle overlaps that aren’t immediately obvious. Let’s break this down clearly:

1. Why Thread.Sleep(-1) Doesn’t Throw an Exception

First, let’s clarify the documentation note: it states that negative values other than Timeout.Infinite (in milliseconds) will throw an error. The key here is that Timeout.Infinite is actually a constant defined as -1. So when you call Thread.Sleep(-1), you’re effectively passing the allowed "infinite timeout" value, which is why no exception is thrown.

2. The Source Code Context

Looking at the ReferenceSource code:

  • The Thread.Sleep(int millisecondsTimeout) method directly delegates to the underlying SleepInternal implementation without any parameter validation on negative values (other than what the internal method handles).
  • The Thread.Sleep(TimeSpan timeout) method adds an extra layer of validation: it converts the TimeSpan to milliseconds first, and throws ArgumentOutOfRangeException only if the resulting value is less than -1 (i.e., more negative than Timeout.Infinite) or exceeds Int32.MaxValue. That’s why passing a TimeSpan equivalent to -1ms won’t throw, but a TimeSpan equivalent to -2ms will.

When you call Thread.Sleep(-2), since Sleep(int) skips the upper-layer validation, the underlying SleepInternal receives an invalid negative value (not equal to -1) and triggers an unhandled exception (which appears as a crash in your code).

3. What Thread.Sleep(-1) Actually Does

Thread.Sleep(-1) (same as Thread.Sleep(Timeout.Infinite)) puts the current thread into an indefinite sleep state. The thread will remain dormant until one of two things happens:

  • Another thread calls Thread.Interrupt() on it, which will wake it up and throw a ThreadInterruptedException.
  • The application process terminates.

This is useful in scenarios where you want a thread to wait indefinitely for an external trigger (though in modern .NET, using synchronization primitives like ManualResetEvent or Task.Delay with cancellation tokens is generally preferred for more control).


内容的提问来源于stack exchange,提问作者Stuart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:53:03