在 Thread.Sleep 期间可以引发 ThreadAbortException 吗?

发布于 2024-08-23 09:50:54 字数 173 浏览 4 评论 0原文

Thread.Abort 可以中断正在睡眠的线程(例如使用 Thread.Sleep(TimeSpan.FromDays(40)) 吗?或者它会等到睡眠时间跨度到期吗?

(备注:FromDays(40) 当然是一个笑话。我知道 Thread.Abort 不是停止线程的推荐方法,我正在使用现在不想重构的遗留代码。)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

や莫失莫忘 2024-08-30 09:50:54

代码胜千字:

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

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

程序在睡眠时间耗尽之前结束。

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.

凉月流沐 2024-08-30 09:50:54

您只能从另一个线程中中止该线程。也就是说,您应该将 Thread 引用存储在某处,然后从睡眠线程以外的线程调用 .Abort

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文