Dan Bailiff
Dan Bailiff

Reputation: 1581

How to cancel peer long-running tasks if one of them stops

I have several long-running Task objects. I'd like them all to just keep running indefinitely. The job of one of these tasks is to self-monitor the system. If something happens outside of normal operating conditions, I'd like it to be able to stop running and somehow signal the other tasks to stop running as well. Is it enough to just use Task.WaitAny(), stop the one thread and the others will stop, or will those other Tasks keep running indefinitely?

Upvotes: 1

Views: 742

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564851

Those Tasks will continue running, unless you explicitly handle cancellation.

The preferred method to handle this is using the new cooperative cancellation support in .NET 4.

The normal method would be to have a continuation on each task that runs when a task fails/faults. It could then have a CancelationTokenSource that gets canceled. Each task can occasionally check to see if it should abort because a cancellation is requested.

Upvotes: 3

Related Questions