Introducing the Task Parallel Library’s new Cancellation Framework
.NET 4’s Task Parallel Library got a face lift for beta 2. This much anticipated library replaces the aging ThreadPool with improvements in both performance and functionality. One such improvement is addressing the ThreadPool’s inability to cancel tasks. As you probably know, there is currently no coherent way to abort a task once it is placed in the old pool.
The Task Parallel Library has always intended to support cancelation, but beta 2 brings a significant change to how it is implemented and exposed. The public face of the new model is the CancellationTokenSource, which contains a CancellationToken. This removes the need for the Task members Cancel, AcknowledgeCancellation, IsCancellationRequested, Current, Parent, and the enumeration TaskCreationOptions.RespectParentCancellation. In its place, many methods now allow an optional CancellationToken to be passed in.
Objects that need to initiate the cancelation of one or more tasks must now hold a reference to the CancellationTokenSource. Tasks that must respond to the cancellation get a reference to the CancellationToken and periodically check its IsCancellationRequested property. Multiple tasks can and should share the same CancellationToken when appropriate. To acknowledge the cancellation request, each task will need to throw an OperationCanceledException.
In prior betas, tasks inherently understand parent/child relationships. These relationships and their associated behavior would be automatically established unless the developer opted-out. In beta 2 that decision has been reversed. Parent/child relationships are only established if the developer asks for it, otherwise each task is considered to be autonomous.
If you choose to use parent/child tasks, you still get features such as exception propagation and parent tasks implicitly waiting for their children to complete. If you don’t, tasks make an excellent drop-in replacement for ThreadPool work items.
Like most unhandled exceptions, TPL exceptions that are unobserved can cause an application to crash. To “observe” an exception, some piece of code must either call Wait on the task or check its Exception property before the task is garbage collected. Beta 2 adds one more option, the UnobservedTaskException event. This gives developers one last chance to deal with the exception before it is bubbled up to a layer where it will cause real damage.
You can read more about the changes in Beta 2 on the Parallel Programming with .NET blog.
Exceptions as flow control
Isn't a cardinal rule of exceptions, "Thou shalt not use exceptions for flow control"?
Re: Exceptions as flow control
When it comes down to it, exceptions are the only tool in .NET have to say "stop processing this function and all the functions that called it". It is also why catching "System.Exception" is a really bad idea.