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.
-
1Does 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
-
1And it's (almost always) a really bad idea to Sleep() in a thread. – H H Apr 26 '11 at 17:17
-
1These 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 Answers
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.
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.

- 554,122
- 78
- 1,158
- 1,373
Consider using the System.Timers.Timer
class. This is a timer that can be stopped if needed.
You can find some good instructions here

- 18,947
- 4
- 64
- 68

- 318
- 4
- 9
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.

- 53,498
- 9
- 91
- 140