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); }
);
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With