开发者

Can a ThreadAbortException be raised during Thread.Sleep?

开发者 https://www.devze.com 2022-12-21 23:22 出处:网络
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 ?

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开发者_StackOverflow.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.)


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号