In a thread, I create some System.Threading.Task
and start each task.
When I do a .Abort()
to kill the thread, the tasks are not aborted.
How can I transmit the .Abort()
to my tasks ?
In a thread, I create some System.Threading.Task
and start each task.
When I do a .Abort()
to kill the thread, the tasks are not aborted.
How can I transmit the .Abort()
to my tasks ?
You can't. Tasks use background threads from the thread pool. Also canceling threads using the Abort method is not recommended. You may take a look at the following blog post which explains a proper way of canceling tasks using cancellation tokens. Here's an example:
Aborting a Task is easily possible if you capture the thread in which the task is running in. Here is an example code to demonstrate this:
I used Task.Run() to show the most common use-case for this - using the comfort of Tasks with old single-threaded code, which does not use the CancellationTokenSource class to determine if it should be canceled or not.
Task are being executed on the ThreadPool (at least, if you are using the default factory), so aborting the thread cannot affect the tasks. For aborting tasks, see Task Cancellation on msdn.
I tried
CancellationTokenSource
but i can't do this. And i did do this with my own way. And it works.And another class of the calling the method:
Tasks have first class support for cancellation via cancellation tokens. Create your tasks with cancellation tokens, and cancel the tasks via these explicitly.