0

简而言之,RunWithTimer 运行一个方法,计数到 10,如果该方法完成的时间超过 10 秒,则将其中止:

void RunWithTimer()
{
  Thread thread = null;
  Action action = () =>
  {
      thread = Thread.CurrentThread;
      method(); //run my method (which shouldn't take more than 10 seconds)
  };

  IAsyncResult result = action.BeginInvoke(null, null);

  //if 10 sec not passed, keep waiting for my method to do it's job
  if (result.AsyncWaitHandle.WaitOne(10000))
      action.EndInvoke(result);

  //if 10 sec is passed, abort the thread that runs my method
  else
      thread.Abort();
}

我在一个名为 MainThread 的线程中调用 RunWithTimer,问题是当我挂起 MainThread 时,一切似乎都暂停了,但是当我恢复它时,10 秒计数器已经过去,并且 RunWithTimer 在它运行 10 秒之前停止该方法。实际上看起来暂停并没有暂停 AsyncWaitHandle.WaitOne(time),可能是因为 WaitOne 使用系统时间,而 MainThread 肯定不会暂停系统时间!

那么我应该怎么做,也暂停 WaitOne..?

4

0 回答 0