c# - 线程. sleep (-1)

标签 c# multithreading

有什么用

 System.Threading.Thread.Sleep(-1)

我希望这会引发异常,正如 Thread.Sleep 的文档所说

The value of timeout is negative and is not equal to Timeout.Infinite in milliseconds, or is greater than Int32.MaxValue milliseconds.

但是,上面的 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 : A constant used to specify an infinite waiting period, for threading methods that accept an Int32 parameter.

关于c# - 线程. sleep (-1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50269871/

相关文章:

c# - 如何获取特定页面类型构建器类型的 EPiServer 页面,并正确填充其所有强类型属性?

c# - VB.NET 代码返回与 C# 代码不同的结果

c# - XDocument 文本节点换行

c# - Form.Show() 没有显示它的子控件

C - __declspec(thread) 变量性能

android - 在单独的线程上运行一段代码

.net - 如何从线程任务返回数据

c# - 使用 Entity Framework 4 选择具有非标量键列表的多行的好方法

c# - 来自 subview 的 MainWindow ViewModel 引用

php - 线程PHP中的全局增量