.netcore 使用多线程Task消费队列进行消费

  WebApiResult为封装公用方法,不是微软自带,此段代码指是做画龙点睛作用,添加队列、异步消费等

  public async Task AuthentDeal()
        {
            //从数据库查询要处理的队列
            var batchList = _MySqlMasterDb.tab1.Where(p => p.is_certifi == -1).ToList();
            if (batchList.Count <= 0)
            {
                return;
            }

            Dictionary<Guid, WebApiResult> resultList = new Dictionary<Guid, WebApiResult>();
            //将查询对象放入队列
            ConcurrentQueue<tab1> searchQueue = new ConcurrentQueue<tab1>();
            foreach (var item in batchList)
            {
                searchQueue.Enqueue(item);
            }
            //设置线程数量
            int threadCount = searchQueue.Count < Environment.ProcessorCount ? searchQueue.Count : Environment.ProcessorCount;
            Task[] tasks = new Task[threadCount];
            for (int i = 0; i < threadCount; i++)
            {
                tasks[i] = Task.Run(() =>
                {
                    WebApiResult taskResult = new WebApiResult();
                    while (searchQueue.TryDequeue(out partners t))
                    {
                        taskResult = VerifyPartners(t).Result;//验证方法
                        if (taskResult != null)
                        {
                            resultList.Add(t.id, taskResult);//验证结果存入字典中
                        }
                    }
                    return taskResult;
                });
            }
            Task.WaitAll(tasks);

            foreach (var item in batchList)
            {
                if (resultList.ContainsKey(item.id))
                {
                    var verifyResult = resultList[item.id];

                    var authResult = JsonConvert.DeserializeObject<Tuple<bool, List<CertificateErrorType>, TencentBankQueryResult, string, bool>>(JsonConvert.SerializeObject(verifyResult.Data));
                //验证完成后业务处理
               //
              //
    
                }
            }
          
        }                   

 

posted @ 2020-07-22 10:05  低调码农哥!  阅读(293)  评论(0编辑  收藏