阻塞线程超过 Int32.MaxValue

Blocking a thread for longer than Int32.MaxValue

我正在做一个项目,该项目需要阻塞 运行 线程的时间跨度可能从一秒到几个月不等。

我想出的方法是使用指定超时的 EventWaitHandle.WaitOne 方法(或其任何兄弟)。问题是所有这些方法都将 Int32 作为参数,将最大块时间限制为大约 25 天。

有人知道解决这个问题的办法吗?我怎样才能阻塞线程超过 Int32.MaxValue 毫秒?

感谢

更新

仅作记录,这是我最终想出的代码片段:

while(_doRun)
{
  // Determine the next trigger time
  var nextOccurence = DetermineNextOccurence();
  var sleepSpan = nextOccurence - DateTime.Now;

  // if the next occurence is more than Int32.MaxValue millisecs away,
  // loop to work around the limitations of EventWaitHandle.WaitOne()
  if (sleepSpan.TotalMilliseconds > Int32.MaxValue) 
  {
    var idleTime = GetReasonableIdleWaitTimeSpan();
    var iterationCount = Math.Truncate(sleepSpan.TotalMilliseconds / idleTime.TotalMilliseconds);
    for (var i = 0; i < iterationCount; i++)
    {
      // Wait for the idle timespan (or until a Set() is called).
      if(_ewh.WaitOne(idleTime)) { break; }
    }
  }
  else
  {
    // if the next occurence is in the past, trigger right away
    if (sleepSpan.TotalMilliseconds < 0) { sleepSpan = TimeSpan.FromMilliseconds(25); }

    // Wait for the sleep span (or until a Set() is called).
    if (!_ewh.WaitOne(sleepSpan))
    {
      // raise the trigger event
      RaiseTriggerEvent();
    }
  }
}

该片段是由专用线程执行的代码。请注意,EventWaitHandle.Set() 仅在应用程序退出或希望取消调度程序时调用。

感谢那些愿意帮助的人。

尝试handle.WaitOne(System.Threading.Timeout.Infinite)

如果您不希望它无限地 运行,请从不同的线程外部触发等待句柄。

更新:

如果您不想使用另一个线程,请使用循环:

bool isTriggered = false;
while (!isTriggered) {
    isTriggered = handle.WaitOne(timeout);
    //Check if time is expired and if yes, break
}

您必须将超时时间跨度分成多个块,以适应 Int32isTriggered 变量将显示句柄是否被触发或是否超时。