简体   繁体   中英

Stopping a Async process from running forever?

Trying to gain a better understanding of Async threads.

AC# application contains this code:

IAsyncResult myResult = cmd.BeginExecuteNonQuery(); //start
while (!myResult.IsCompleted)
{
      myResult.AsyncWaitHandle.WaitOne(65000);
}
cmd.EndExecuteNonQuery(myResult); //end

My understanding is that the program will wait until the myResult returns true (IsComplete).

When the myResult never returns true (ie the cmd runs forever) does the aSync timeout? Or will it just keep running? How do I stop it from running forever?

The best way to keep it from running forever is to specify a timeout limit that you manage.

For example:

DateTime dtStart = DateTime.Now;
const int TIMEOUT_SECONDS = 120;

while (!myResult.IsCompleted)
{
      if (DateTime.Now.Subtract(dtStart).TotalSeconds > TIMEOUT_SECONDS)
      {
           // Cleanup and bail 
      }
      myResult.AsyncWaitHandle.WaitOne(65000);
}

The MSDN documentation seems pretty unambiguous; the documentation says that the WaitOne method will wait until a signal is returned (your target method does something and exits) or the timespan elapses. You can make it wait forever (Timespan.Infinite or -1) or return immediately (0).

@competent_tech's answer illustrates this - the thread will block for your timespan, then, if the total time has passed, you can leave the while loop, otherwise wait some more.

Infact, you probably don't even need the while loop - if you set a timespan you are happy with and that elapses, the thread will resume and you can decide what to do next.

So to answer your question, yes, the async will timeout based on that parameter.

Every so often I have to go back and read Joe Albahari's guide to threading to remember how it all works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM