user192472
user192472

Reputation: 745

Can a ThreadAbortException be raised during Thread.Sleep?

Can Thread.Abort interrupt a thread that is sleeping (using, say, Thread.Sleep(TimeSpan.FromDays(40)) ? Or will it wait until the sleep time span has expired ?

(Remarks: FromDays(40) is of course a joke. And I know Thread.Abort is not a recommended way to stop a thread, I'm working with legacy code that I don't want to refactor for now.)

Upvotes: 1

Views: 3332

Answers (2)

João Angelo
João Angelo

Reputation: 57688

Code is worth a thousand words:

public static void Main(string[] args)
{
    var sleepy = new Thread(() => Thread.Sleep(20000));

    sleepy.Start();
    Thread.Sleep(100);
    sleepy.Abort();
    sleepy.Join();
}

The program ends before the sleep time is exhausted.

Upvotes: 6

Kerido
Kerido

Reputation: 2940

You can abort the thread from another thread only. That is, you should store the Thread reference somewhere and then call .Abort from a thread other than the one which is sleeping.

Upvotes: -2

Related Questions