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 ?
This sort of thing is one of the logistical reasons why
Abort
is deprecated. First and foremost, do not useThread.Abort()
to cancel or stop a thread if at all possible.Abort()
should only be used to forcefully kill a thread that is not responding to more peaceful requests to stop in a timely fashion.That being said, you need to provide a shared cancellation indicator that one thread sets and waits while the other thread periodically checks and gracefully exits. .NET 4 includes a structure designed specifically for this purpose, the
CancellationToken
.I use a mixed approach to cancel a task.
Checkout an example below:
You can use a
CancellationToken
to control whether the task gets cancelled. Are you talking about aborting it before it's started ("nevermind, I already did this"), or actually interrupting it in middle? If the former, theCancellationToken
can be helpful; if the latter, you will probably need to implement your own "bail out" mechanism and check at appropriate points in the task execution whether you should fail fast (you can still use the CancellationToken to help you, but it's a little more manual).MSDN has an article about cancelling Tasks: http://msdn.microsoft.com/en-us/library/dd997396.aspx
You should not try to do this directly. Design your tasks to work with a CancellationToken, and cancel them this way.
In addition, I would recommend changing your main thread to function via a CancellationToken as well. Calling
Thread.Abort()
is a bad idea - it can lead to various problems that are very difficult to diagnose. Instead, that thread can use the same Cancellation that your tasks use - and the sameCancellationTokenSource
can be used to trigger the cancellation of all of your tasks and your main thread.This will lead to a far simpler, and safer, design.
Like this post suggests, this can be done in the following way:
Although it works, it's not recommended to use such approach. If you can control the code that executes in task, you'd better go with proper handling of cancellation.
To answer Prerak K's question about how to use CancellationTokens when not using an anonymous method in Task.Factory.StartNew(), you pass the CancellationToken as a parameter into the method you're starting with StartNew(), as shown in the MSDN example here.
e.g.