Parallel.ForEach 并行循环的使用

本文介绍了一种通过使用Parallel.ForEach替代普通foreach循环来提高处理大量数据时的程序性能的方法。通过对比两种方法的实际运行时间,展示了并行循环可以有效减少耗时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

业务开发,使用foreach遍历几千条数据,并有一定的业务逻辑处理,执行非常耗时,想了一个优化办法就是使用Parallel.ForEach 并行循环:

 

正常foreach的写法:

#region
//foreach (var InspCategItem in InspCategList)
//{
// #region
// HiddenDangerModelTV hdtvItem = new HiddenDangerModelTV();
// hdtvItem.text = InspCategItem.Name;
// hdtvItem.nodeType = (int)nodeTypeEnum.检查类别;
// hdtvItem.id = InspCategItem.Std_InspectionCategoryID;
// hdtvItem.hasChildren = true;
// hdtvItem.expanded = false;
// hdtvItem.Children = new List<HiddenDangerModelTV>();

// if (isRiskEvalSubItem)
// {
// hdtvItems.Add(hdtvItem);
// }
// else
// {
// if (isHaveEvalItem == 1)
// {
// var isHaveItemList = _rplService.GetIsHaveEvalItems(siteGroupId);
// if (isHaveItemList.Contains(hdtvItem.id))
// {
// hdtvItems.Add(hdtvItem);
// }
// }
// else if (isHaveEvalItem == 2)
// {
// //var isHaveItemList = _rplService.GetIsHaveEvalItems(siteGroupId);
// //if (!isHaveItemList.Contains(hdtvItem.id))
// //{
// // hdtvItems.Add(hdtvItem);
// //}
// }
// }

// FindInspItemImport(hdtvItem, itemCheckIdStr, isRiskEvalSubItem, siteGroupId, isHaveEvalItem);
// if (isHaveEvalItem == 2)
// {
// if (hdtvItem.Children.Count > 0)
// {
// hdtvItems.Add(hdtvItem);
// }
// }
// #endregion
//}
#endregion

 

第二种使用并行循环:

#region
Parallel.ForEach(InspCategList, InspCategItem =>
{
#region
HiddenDangerModelTV hdtvItem = new HiddenDangerModelTV();
hdtvItem.text = InspCategItem.Name;
hdtvItem.nodeType = (int)nodeTypeEnum.检查类别;
hdtvItem.id = InspCategItem.Std_InspectionCategoryID;
hdtvItem.hasChildren = true;
hdtvItem.expanded = false;
hdtvItem.Children = new List<HiddenDangerModelTV>();

if (isRiskEvalSubItem)
{
hdtvItems.Add(hdtvItem);
}
else
{
if (isHaveEvalItem == 1)
{
var isHaveItemList = _rplService.GetIsHaveEvalItems(siteGroupId);
if (isHaveItemList.Contains(hdtvItem.id))
{
hdtvItems.Add(hdtvItem);
}
}
else if (isHaveEvalItem == 2)
{
//var isHaveItemList = _rplService.GetIsHaveEvalItems(siteGroupId);
//if (!isHaveItemList.Contains(hdtvItem.id))
//{
// hdtvItems.Add(hdtvItem);
//}
}
}

FindInspItemImport(hdtvItem, itemCheckIdStr, isRiskEvalSubItem, siteGroupId, isHaveEvalItem);
if (isHaveEvalItem == 2)
{
if (hdtvItem.Children.Count > 0)
{
hdtvItems.Add(hdtvItem);
}
}
#endregion
});
#endregion

 

System.Diagnostics.Stopwatch Watch1 = new System.Diagnostics.Stopwatch();
Watch1.Start();

中间是上面的两段代码的执行时间统计

Watch1.Stop();
var time = Watch1.ElapsedMilliseconds;

执行得出的结果:只使用foreach需要耗时15秒,使用Parallel.ForEach需要耗时11秒,所以说Parallel.ForEach效率比oreach高

当然这个执行时间还是比较长,还得需要优化,这个优化就得在方法内部的业务逻辑的代码优化了

 

转载于:https://www.cnblogs.com/redfull/p/9633659.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值