Thread.Sleep(-1)为何不抛异常?其实际作用是什么?
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 underlyingSleepInternalimplementation 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 throwsArgumentOutOfRangeExceptiononly if the resulting value is less than -1 (i.e., more negative thanTimeout.Infinite) or exceedsInt32.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 aThreadInterruptedException. - 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

