Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TaskEx.WhenAll and Exceptions

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.

like image 647
John Avatar asked May 09 '26 14:05

John


1 Answers

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;
like image 95
svick Avatar answered May 12 '26 07:05

svick