Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top