Parallel.ForEach Más lento que ForEach
Aquí está el código:
using (var context = new AventureWorksDataContext())
{
IEnumerable<Customer> _customerQuery = from c in context.Customers
where c.FirstName.StartsWith("A")
select c;
var watch = new Stopwatch();
watch.Start();
var result = Parallel.ForEach(_customerQuery, c => Console.WriteLine(c.FirstName));
watch.Stop();
Debug.WriteLine(watch.ElapsedMilliseconds);
watch = new Stopwatch();
watch.Start();
foreach (var customer in _customerQuery)
{
Console.WriteLine(customer.FirstName);
}
watch.Stop();
Debug.WriteLine(watch.ElapsedMilliseconds);
}
El problema es,Parallel.ForEach
tarda unos 400 ms frente a un @ normforeach
, que tarda unos 40 ms. ¿Qué estoy haciendo mal exactamente y por qué esto no funciona como esperaba?