ManualResetEventSlim.Wait()的TimeSpan与int超时参数差异探究
ManualResetEventSlim.Wait(int) and ManualResetEventSlim.Wait(TimeSpan) Great question—let’s break down the practical and implementation differences between these two overloads, since their wildly different timeout limits are just the tip of the iceberg.
1. Hard Timeout Limits
The most obvious gap is the maximum wait time each supports:
Wait(int millisecondsTimeout)caps out at 24.85 days (sinceint.MaxValueis 2,147,483,647 milliseconds). If you try to pass a value larger than this (or a negative number that’s notTimeout.Infinite), you’ll get anArgumentOutOfRangeException.Wait(TimeSpan timeout)can handle waits up to ~10.6 million days (fromTimeSpan.MaxValue), which is effectively unlimited for most real-world scenarios.
2. Code Readability & Intent
- The int overload is great for short, straightforward timeouts where milliseconds are intuitive. For example:
// Wait 5 seconds for the event to signal resetEvent.Wait(5000); - The TimeSpan overload shines when you want to make your wait time explicit and human-readable, especially for longer durations. No need to calculate milliseconds manually:
This makes your code self-documenting—anyone reading it immediately knows you’re waiting 30 days, not trying to parse what 2592000000 milliseconds means.// Wait 30 days for the event (something you can't do with the int overload) resetEvent.Wait(TimeSpan.FromDays(30));
3. Internal Implementation Quirks
Under the hood, the int overload converts the millisecond value to a TimeSpan and calls the TimeSpan overload in most cases—but there’s a catch:
- For very short timeouts (or
Timeout.Infinite), the int overload might take a slightly more optimized path in some .NET runtime versions, avoiding extraTimeSpanallocation/parsing overhead. That said, this is a micro-optimization and rarely matters unless you’re callingWaitin a tight loop millions of times. - If you pass
Timeout.Infinite(-1) to the int overload, it maps directly toTimeout.InfiniteTimeSpanfor the TimeSpan version—so behavior is identical here.
4. Avoiding Overflow Bugs
A common pitfall with the int overload is accidental overflow when calculating milliseconds from longer durations. For example:
// This will overflow (2592000000 > int.MaxValue) and cause unexpected behavior resetEvent.Wait((int)TimeSpan.FromDays(30).TotalMilliseconds);
This either throws an OverflowException (in checked contexts) or wraps around to a negative number (in unchecked contexts), which will be treated as an invalid timeout. Using the TimeSpan overload eliminates this risk entirely.
Hope that clears up when to use each overload! It all boils down to your timeout length needs and how readable you want your code to be.
内容的提问来源于stack exchange,提问作者Corio

