• c# Parallel.For 循环内多线程并行操作


    记录一下使用方法

    一般在方法开销很大的时候,用并行才能体现出效率。当然这是无序的,慎用吧。

    这是我们公司的一个业务场景记录一下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 更多使用方法可以看

    C#并行编程-Parallel - 释迦苦僧 - 博客园

  • 相关阅读:
    为什么说log用占位符比用字符串连接比较好
    RabbitMQ
    【Python百日进阶-数据分析】Day119 - Plotly Figure参数: 散点图(一)
    产业集群的转型升级需要各个方面的协同转型——以河北吉力宝为例
    Nginx配置ssl证书实现https访问
    用好 DIV 和 API,在前端系统中轻松嵌入数据分析模块
    [强化学习总结6] actor-critic算法
    数字人直播软件排名推荐,铭顺科技数字人品牌抢占“日不落”流量新技能
    高并发之缓存
    leetCode 198.打家劫舍 动态规划
  • 原文地址:https://blog.csdn.net/qq_39788123/article/details/125498934