You are right! So what's about revision v2 ?
public static void Foreach<T>(ICollection<T> source, Action<T> action)
{
var countdown = new CountdownEvent(source.Count);
List<Exception> exceptions = null;
foreach (var item in source)
{
ThreadPool.QueueUserWorkItem(state =>
{
var closure = (T)state;
try
{
action(closure);
}
catch (Exception ex)
{
if (exceptions == null)
lock (countdown)
{
if (exceptions == null)
exceptions = new List<Exception>();
}
exceptions.Add(ex);
}
finally
{
countdown.Signal();
}
}, item);
}
countdown.Wait();
if (exceptions != null)
throw new AggregateException(exceptions);
}