• Foreach多线程问题


    因为以前对天气的第三方API 封装不够友好,经常出问题,也很难定位问题的出处,所以近期花了大时间,对天气的API 进行了重新封装。一开始只是封装了一个对位的接口,就是一次只能获取一个地址的天气;后来老大Review 代码后,提出存在多地址的需求,对外就多提供了一个支持都地址查询的接口,内部其实就是实现一个遍历的过程。这里就是记录遍历发生问题的演变。

    最开始代码,这种方法是单线程的,执行时间非常的长

    var result = new List<WeatherModel>();
    if (query.Count > 100)
    {
    	throw new WeatherException("Search data cannot exceed 100.");
    }
    
    foreach (var query in querys)
    {
    	var weather = await GetWeather(item);
    	if (weather != null)
    	{
          result.Add(weather);
    	}
    }
    

      

    经过优化后,这种方法是根据设定的线程数跑,会提速很多

    var result = new List<WeatherModel>();
    if (query.Count > 100)
    {
      throw new WeatherException("Search data cannot exceed 100.");
    }
    
    Parallel.ForEach(query, new ParallelOptions()
    {
    	MaxDegreeOfParallelism = WeatherConfiguration.MaxDegreeOfParallelism
    }, item => Task.Run(async () =>
    {
    	try
    	{
    		var weather = await GetWeather(item);
    		if (weather != null)
    		{
    			result.Add(weather);
    		}
    	}
    	catch (Exception ex)
    	{
    		GetWeathersException(ex, isNeedException);
    	}
    
    }).GetAwaiter().GetResult());
    

      上述的方法虽然性能上上来了,但是发现了一个问题,如下图

    最终版

     if (query.Count > 100)
     {
         throw new WeatherException("Search data cannot exceed 100.");
     }
    
     return query.AsParallel<WeatherQueryModel>()
      .WithDegreeOfParallelism(WeatherConfiguration.MaxDegreeOfParallelism) .Select<WeatherQueryModel, WeatherModel>(item => GetWeather(item, isNeedException)
      .ConfigureAwait(false).GetAwaiter().GetResult() ).ToList();

      

  • 相关阅读:
    CXF JaxWsDynamicClientFactory 错误:编码GBK的不可映射字符
    关于springboot配置DataSource
    Spring Boot2.0加载多个数据源
    Kettle配置发送邮件
    推荐几个不错的VUE UI框架
    vue基础语法一
    Maven在Eclipse下构建多模块项目过程
    利用eclipse把jar包安装到本地仓库
    设计模式之策略模式
    设计模式之观察者模式
  • 原文地址:https://www.cnblogs.com/zhihang/p/11280024.html
Copyright © 2020-2023  润新知