Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abort a thread when it is sleeping

Tags:

c#

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.

like image 381
Tirmit Avatar asked Nov 27 '22 12:11

Tirmit


2 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.

like image 183
spender Avatar answered Dec 19 '22 00:12

spender


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.

like image 45
Reed Copsey Avatar answered Dec 19 '22 01:12

Reed Copsey