Tirmit
Tirmit

Reputation: 183

How to abort a thread when it is sleeping

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.

Upvotes: 4

Views: 11293

Answers (4)

Mark Dornian
Mark Dornian

Reputation: 416

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

You can find some good instructions here

Upvotes: 6

spender
spender

Reputation: 120380

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.

Upvotes: 15

Reed Copsey
Reed Copsey

Reputation: 564333

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.

Upvotes: 7

Steve Townsend
Steve Townsend

Reputation: 54128

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.

Upvotes: 2

Related Questions