How to pause an AsyncWaitHandle.WaitOne(time) countdown

183 Views Asked by At

To describe briefly, the RunWithTimer runs a method, counts to 10, if the method took longer than 10 seconds to complete aborts it:

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();
}

I call RunWithTimer in a thread called MainThread, the problem is when I suspend the MainThread, everything seems paused but when I resume it, the 10 seconds counter has passed and RunWithTimer stops the method before it runs for 10 seconds. Actually it looks like the suspending does not suspend the AsyncWaitHandle.WaitOne(time), maybe because WaitOne uses system time and system time is surely not suspended while MainThread is!

So what should I do, to suspend the WaitOne too..?

0

There are 0 best solutions below