Thread.Abort 与 Thread.Interrupt [英] Thread.Abort vs Thread.Interrupt

查看:87
本文介绍了Thread.Abort 与 Thread.Interrupt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我需要取消某个线程上的某些操作,我应该在什么时候使用 Thread.AbortThread.Interrupt.我阅读了有关它的文档,但不确定我应该在两个场景之间使用哪个特定调用.

If I need to cancel some operation on a thread, when should I use Thread.Abort vs Thread.Interrupt. I read the documentation on it but not sure which scneario should i use a particular call between two.

如果有任何第三种方法,请让我知道它的利弊.

If there is any third way of doing it, please let me knwo about it too with pro and cons.

推荐答案

我会不惜一切代价避免使用 Thread.Abort.自 .NET 2.0 以来,它的行为更加安全和可预测,但它仍然存在一些非常严重的缺陷.托管代码中的大多数中止都可以是安全的,但不是全部.例如,我认为如果在静态构造函数的处理过程中触发了中止请求,就会存在一些微妙的问题.没关系,带外异常随时可能发生,这让您几乎无法控制关闭安全点的位置.

I would avoid using Thread.Abort at all costs. Its behavior is much safer and predictable since .NET 2.0, but there are still some pretty serious pitfalls with it. Most of the aborts inside managed code can be made safe, but not all of them. For example, I believe there are some subtle problems if an abort request is triggered during the processing of a static constructor. Nevermind, the fact that the out-of-band exception can occur at anytime giving you little control over defining where the safe points for shutdown are located.

有几种可接受的方式可以优雅地终止线程.

There are several acceptable ways to terminate a thread gracefully.

  • 使用Thread.Interrupt
  • 轮询停止标志
  • 使用WaitHandle 事件
  • 专门的 API 调用

我在我的回答中讨论了这些方法这里.

I discuss these methods in my answer here.

这篇关于Thread.Abort 与 Thread.Interrupt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆