Thread supports interrupt. Why doesn't Task?
From my (uninformed) perspective, it seems reasonable to allow Task to support interruption:
- If the Task isn't currently being executed on a Thread, calling task.Interrupt() will set a TaskInterruptException to be thrown when the Task is scheduled.
- Otherwise, the TaskInterrupException will be thrown in the thread executing the task, which exception will either be caught within the task or added to the AggregateException at the top. I guess this feature would require the task to know the executing thread (is this unreasonable?)
Do the pieces needed to implement this feature already exist, or would this require changes to the language implementation?
Addition:
I have read numerous questions on SO that discuss killing/aborting Tasks, with their associated answers discussing CancellationToken
and the (discouraged) Thread.Abort
approach.
In my own fiddling, I discovered that registering Thread.Interrupt with CancellationToken.Register doesn't interrupt the thread running in the task, but instead interrupts the thread calling cancel on the token.
So, as I see it, there is still a need for a sanctioned feature allowing the developer to ensure a Task can be (gently) terminated.
I will also add (lest someone say "re-write your Tasks to take CancellationTokens") that this feature is particularly valuable in situations where the developer does not own the code being executed in the Tasks.
And, on matter of principle, it seems that there should be a way for the executor of the Task to be able to provide a guarantee of cancellation, rather than depending on the implementer of the Task to do things correctly with a cancellation token.
Another addition:
Regardless of the risks, the C# API supports Thread.Abort
and Thread.Interrupt
. So my question is, essentially, why doesn't Task
support the same API (with the same inherent risks)?
Update
This post has been marked as a duplicate of this question. However, I had already read the referenced question before posting this one (and all of the answers) - this question is not a duplicate, but a related question seeking additional information. That question asks "can you abort" and the answers are essentially "you should not abort" - my question asks "Given that interrupt is better than abort, why isn't interrupt a supported feature? What mechanical hurdles prohibit this feature?". According to this question, there are important differences between interrupting and aborting a thread, and that interrupt is much preferred.