4

I need to stop a thread ,but if it should sleep for 8 sec ,and I want to abort it ,it will continue sleeping for 8 sec,and only then stops.

Tirmit
  • 183
  • 1
  • 3
  • 15
  • 1
    Does it matter whether it is aborted during or after the sleep? – Szymon Rozga Apr 26 '11 at 16:14
  • Have you considered waking it up? ie. using something that will force it out of the sleep? – Lasse V. Karlsen Apr 26 '11 at 16:15
  • It's a *really* bad idea to abort threads. See http://stackoverflow.com/questions/1559255/whats-wrong-with-using-thread-abort – Jim Mischel Apr 26 '11 at 17:04
  • 1
    And it's (almost always) a really bad idea to Sleep() in a thread. – H H Apr 26 '11 at 17:17
  • 1
    These guys are right; revisit your threading strategy entirely. Sleeping and aborting threads are almost never the right thing to do; doing them both together is a terrible idea. You should have a carefully architected solution whereby one thread can politely request another to take itself down, and the other thread guarantees to do so promptly. – Eric Lippert Apr 26 '11 at 18:54

4 Answers4

15

Use a ManualResetEvent:

ManualResetEvent mre=new ManualResetEvent(false);
//......
var signalled=mre.WaitOne(TimeSpan.FromSeconds(8));
if(!signalled)
{
    //timeout occurred
}

elsewhere (before the 8 seconds is up):

mre.Set(); //unfreezes paused Thread and causes signalled==true

and allow the unblocked thread to terminate gracefully. Thread.Abort is evil and should be avoided.

Community
  • 1
  • 1
spender
  • 117,338
  • 33
  • 229
  • 351
7

You can't (safely) abort a thread while it's asleep. You should just check for your abort condition as soon as your blocking completes, and exit at that point.

There really is no disadvantage to this in most cases, anyways, as the thread will use very little resources while blocked.

If you must "abort" sooner, you could, instead, use a different mechanism for blocking. Sleeping is rarely the correct option - a wait handle will likely be able to provide the same functionality, and give a means for the other thread to signal that it should stop blocking immediately.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
6

Consider using the System.Timers.Timer class. This is a timer that can be stopped if needed.

You can find some good instructions here

qqx
  • 18,947
  • 4
  • 64
  • 68
Mark Dornian
  • 318
  • 4
  • 9
2

Use an AutoResetEvent timed Wait instead of Sleep, signal the AutoResetEvent using Set when you wish to interrupt the waiting thread, otherwise the timer expires.

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140