What will happen to the remaining tasks when TaskFactory.ContinueWhenAny(Task[], Action(Task)) is invoked? DO the remaining tasks get cancelled or will be running in the background after a particular task is completed first? How do we cancel them if they are running in the background?
1 Answers
3
votes
The remaining tasks run as normal. This continuation triggers when the first Task
completes.
Cancel the remaining tasks like this:
var tknSource = new CancellationTokenSource();
List<Task> tasks = new List<Task>();
for(int i = 0; i < 50; i++)
{
tasks.Add(Task.Run(DoWork(tknSource.Token))); //pass the token to the tasks
}
TaskFactory.ContinueWhenAny(tasks.ToArray(), p => tknSource.Cancel()); //requests a cenllation on tasks that are still running
Note that you can only request cancellation. DoWork
has to observe and act upon the token as it changes state.
Check out the MSDN article on Task Cancellation for more details
Task
in general. Only if it cooperates. – usr