TaskEx.WhenAll and Exceptions

1k views Asked by At

I'm constrained to using the .NET 4.0 framework and Async CTP Extensions to do something like the following:

     var dataTasks = _tasks.Select(t => t.GetData(keys));

     var results = TaskEx.WhenAll(dataTasks).Result.ToList();

where _tasks is a list of objects that each provide a GetData method that returns a Task<Data>.

My problem is that one of the dataTasks is throwing an exception and tanking the whole. I'd like to be able to inspect the results of each dataTask and check the results, logging any exception and then continuing on with any valid results. I'm unsure now to go about it though. Any help would be greatly appreciated.

2

There are 2 answers

4
svick On BEST ANSWER

One way to do this would be to use a trivial ContinueWith() to change a potentially faulting Task<T> into a successful Task<Task<T>>. If you then use WhenAll().Result on that (or await WhenAll()), you'll get Task<T>[], which is exactly what you need:

var dataTasks = _tasks.Select(t => t.GetData(keys).ContinueWith(c => c));

Task<T>[] results = Task.WhenAll(dataTasks).Result;
4
usr On

TaskEx.WhenAll(dataTasks) is your combined task. It might be faulted.

When calling Result this cause the exception to be thrown. So don't do that. Examine the Exception or IsFaulted properties.