ThrowIfCancellationRequested() 与 Abort()

ThrowIfCancellationRequested() vs Abort()

我想达到什么目的?

I am trying to cancel a long running task from within another task using a CancellationToken. It's impossible for me to handle the cancellation and throw in the long running task because it will never touch the code that handles the cancellation (the task processes a bad regex pattern that takes forever anyway this is not important). I tried to handle from within another Task and poll for the cancellation request, and when I call ThrowIfCancellationRequested() it actually throws in that thread. So the long running task is still alive and hanging.

我是如何解决这个问题的

Well instead of using token's ThrowIfCancellationRequested() i acually called Abort() on the long running task's Thread and it works like charm.

我的问题是:我很确定它不是很优雅,我想知道我在那里做的是否可以,我还能如何处理这种情况?

Thread.Abort is evil 因为它非常危险。 .NET(以及我知道的任何其他平台)中的取消是合作的。要么让操作按需自行取消,要么将其隔离,以便您可以忽略它。