记录一下使用方法
一般在方法开销很大的时候,用并行才能体现出效率。当然这是无序的,慎用吧。
这是我们公司的一个业务场景记录一下Parallel.For的使用方法
条件:开始时间、结束时间
实现思路:使用线程并行循环 每天的时间筛选数据并填充在总集合内(当然日期肯定是无序的)
var dateList = new List<DateTime>(); //时间集合
//获取时间范围内每天的时间,填充到datelist
while (beginDate <= endDate)
{
dateList.Add(beginDate);
beginDate = beginDate.AddDays(1);
}var allRecordList = new ConcurrentBag<List<TelWorkRecordDto>>();//总集合
var op = new ParallelOptions
{
MaxDegreeOfParallelism = 4,//并发数
};//多线程并行循环
//参数1:应该是起始索引
//参数2:循环总长度
//参数3:并发数
//参数4:当前索引
ParallelLoopResult result = Parallel.For(0, dateList.Count, op, (i) =>
{
var currDate = dateList[i];//当前天的时间//获取当前时间一天内的数据
var portion = GetCustomerRecord(currDate.ToString("yyyy-MM-dd HH:mm:ss"), currDate.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss"));
if (portion != null && portion.Any())
{
allRecordList.Add(portion);
}
AddLog(e, $"{currDate.ToString("yyyy-MM-dd")}_查询结束");
});Console.WriteLine("是否完成:{0}", result.IsCompleted);
Console.WriteLine("最低迭代:{0}", result.LowestBreakIteration);
Parallel.ForEach
List<int> lists = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; Parallel.ForEach(lists, i => { Console.WriteLine(i); });
关于Parallel 更多使用方法可以看