TheJediCowboy
TheJediCowboy

Reputation: 9222

Task Parallel Library WaitAll Exception Handling

I am working with the Task Parallel Library and I am using the Task Factory to create and start a list of new tasks. After starting the tasks, I make a call to Task.WaitAll(...) to wait until all the Tasks return. The code looks similar to the following.

Tasks<MyClass>[] tasks = .../Create List of Tasks and Start using TaskFactory.StartNew(..) etc.

Task.WaitAll(tasks);         //Wait until all tasks complete before continuing. 

When my tasks return and are completed, if they meet certain criteria, the results will be aggregated into a list to be handled at a later time. While each tasks is running, certain exceptions may be thrown which will 'disqualify' the task result from being added to the aggregate list. I want to be able to throw exceptions within the executing task, and the task to no longer run.

I am aware that there are features such as cancellation tokens and cancellation sources for being able to handle certain events, but they don't seem to allow me to do what I want. Althought it doesn't exist, I would have liked functionality such as subscribing to event handlers on the tasks such as task.OnException or task.OnError,etc. What are my options for accomplishing this functionality with TPL?

Upvotes: 2

Views: 1859

Answers (2)

Alex F
Alex F

Reputation: 3539

You can break a Task execution a little bit more into parts with help of TaskCompletionSource. Then you can expose events (?) that will be raised just before TaskCompletionSource will SetResult or TryToSetException methods run.

Upvotes: 0

James
James

Reputation: 2841

After a Task has finished running, you can check the Task.Exception property.

Task.Exception Property

If there was an unhandled exception running the Task, Task.Exception will not be null, it will be a System.AggregateException which will contain the details for one of more exceptions that occured.

You might also try using Task.ContinueWith on each Task, passing in a new Task and a flag of TaskContinuationOptions.OnlyOnFaulted. This new task is executed only if there was an unhandled exception in the original Task.

Upvotes: 2

Related Questions