如何像中止线程一样中止任务(Thread.Abort 方法)?

编程入门 行业动态 更新时间:2024-10-11 05:31:25
本文介绍了如何像中止线程一样中止任务(Thread.Abort 方法)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我们可以像这样中止Thread:

Thread thread = new Thread(SomeMethod); . . . thread.Abort();

但是我可以以相同的方式中止 Task(在 .Net 4.0 中)而不是通过取消机制.我想立即终止任务.

But can I abort a Task (in .Net 4.0) in the same way not by cancellation mechanism. I want to kill the Task immediately.

推荐答案

  • 你不应该使用 Thread.Abort()
  • 任务可以取消但不能中止.
  • Thread.Abort() 方法是(严重)已弃用.

    The Thread.Abort() method is (severely) deprecated.

    线程和任务在停止时都应该合作,否则你会冒着让系统处于不稳定/未定义状态的风险.

    Both Threads and Tasks should cooperate when being stopped, otherwise you run the risk of leaving the system in a unstable/undefined state.

    如果您确实需要运行一个进程并从外部杀死它,唯一安全的选择是在单独的 AppDomain 中运行它.

    If you do need to run a Process and kill it from the outside, the only safe option is to run it in a separate AppDomain.

    这个答案是关于 3.5 及更早版本的.

    This answer is about 3.5 and earlier.

    从那时起,线程中止处理得到了改进,a.o.通过改变 finally 块的工作方式.

    Thread-abort handling has been improved since then, a.o. by changing the way finally blocks work.

    但是 Thread.Abort 仍然是您应该始终尽量避免的可疑解决方案.

    But Thread.Abort is still a suspect solution that you should always try to avoid.

    更多推荐

    如何像中止线程一样中止任务(Thread.Abort 方法)?

    本文发布于:2023-11-13 04:29:10,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1583429.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:线程   方法   Thread   Abort

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!