阻塞线程的时间超过Int32.MaxValue

本文关键字:Int32 MaxValue 时间 线程 | 更新日期: 2023-09-27 18:18:24

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

我想到的方法是使用指定超时的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()只在应用程序退出或希望取消调度程序时调用。

感谢那些愿意帮助我的人。

阻塞线程的时间超过Int32.MaxValue

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

如果你不希望它无限地运行,可以从另一个线程外部触发等待句柄。

更新:

如果你不想使用其他线程,使用循环:

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

您必须将超时时间划分为适合Int32的多个块。isTriggered变量将显示句柄是否被触发或是否超时。

相关文章: