我想使用Parallel.ForEach在List<T>上的强大功能作为验证例程。该列表被迭代以确保属性不小于1。如果验证发现在验证方法调用中返回的错误,则创建一个bool设置为false。有人告诉我,这段代码是有问题的,因为bool是一个原始的,而不是线程安全的。有什么方法可以利用Parallel.ForEach在一个拥有大量内核和内存的服务器上的强大功能,并确保它在线程安全方面正常工作吗?
public static bool IsValid(List<Airport> entities)
{
bool isValid = true;
Parallel.ForEach<Airport>(entities, entity =>
{
// userId can't be less than 1
if (entity.userId < 1)
{
SiAuto.Main.LogMessage("Airport {0}: invalid userId {1}", entity.airportId, entity.userId);
isValid = false;
System.Diagnostics.Debugger.Break();
}
});
return isValid;
}发布于 2015-07-04 20:13:10
你可以用PLINQ做到这一点:
public static bool IsValid(List<Airport> entities)
{
return !entities.AsParallel().Any(entity => entity.UserId < 1);
}但是,由于并行运行的部分太小,您将得不到任何改进,因此应该坚持使用常规的foreach (或LINQ):
public static bool IsValid(List<Airport> entities)
{
return !entities.Any(entity => entity.UserId < 1);
}发布于 2015-07-04 20:09:08
如果列表足够大,我会使用PLINQ方法使用Enumerable.Any或Enumerable.All
return !entities.AsParallel().Any(x => x.UserId < 1);或
return entities.AsParallel().All(x => !(x.UserId < 1));通常,当使用管道式执行时,我发现PLINQ比Parallel类更合适,因为它消除了在并行循环中更新共享资源的需要。
注意,您应该对代码进行基准测试,以确保并行性是值得的。在很多情况下,如果名单不够大,这可能会降低业绩。
https://stackoverflow.com/questions/31224072
复制相似问题