Search code examples
c#multithreadingsleepabort

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


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.