如何暂停AsyncWaitHandle.WaitOne(时间)倒计时

时间:2016-07-20 10:49:06

标签: c# multithreading asynchronous waitone

简要描述一下,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(时间), 也许是因为WaitOne使用系统时间,而MainThread确实没有暂停系统时间!

那么我该怎么办呢,暂停WaitOne ......?

0 个答案:

没有答案