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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With