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

How to abort a Task like aborting a Thread (Thread.Abort method)?(如何中止任务,如中止线程(Thread.Abort 方法)?)

本文介绍了如何中止任务,如中止线程(Thread.Abort 方法)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

We could abort a Thread like this:

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

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.

解决方案

  1. You shouldn't use Thread.Abort()
  2. Tasks can be Cancelled but not aborted.

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.

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.


This answer is about .net 3.5 and earlier.

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

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


And in .net Core (.net 5+) Thread.Abort() will now throw a PlatformNotSupportedException .

Kind of underscoring the 'deprecated' point.

这篇关于如何中止任务,如中止线程(Thread.Abort 方法)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何中止任务,如中止线程(Thread.Abort 方法)?

基础教程推荐