Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel Foreach with large list throws exception

I have a large list (1000 or more) and I'm using Parallel.Foreach to loop it, but I get this exception:

System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at
System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) at
System.Threading.Tasks.Task.Wait()

Please let me know why I get this exception and give me a solution to resolve it, and how I can improve performance of parallel foreach?

var results = new List<BO>();
var localLockObject = new object();

Parallel.ForEach(
  emails,
  () => new List<BO>(), (email, state, localList) =>
  {
      var item = new BO();
      localList.Add(item.Validate(email));
      return localList;
  },
  finalResult => { lock (localLockObject) results.AddRange(finalResult); }
);
like image 902
KaKa Avatar asked May 25 '26 09:05

KaKa


1 Answers

Your Parallel.ForEach declaration seems to fine, I'm not sure this is the place generating the exception.

However, a better solution for this use case would be to use PLINQ which won't require synchronization:

var result = emails.AsParallel()
                   .Select(email => 
                    { 
                       var item = new BO();
                       return item.Validate(email);
                    }).ToList();
like image 153
Yuval Itzchakov Avatar answered May 30 '26 23:05

Yuval Itzchakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!