zoukankan      html  css  js  c++  java
  • 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();

      

  • 相关阅读:
    hdu 2842 Chinese Rings
    Codeforces Round #118 (Div. 1) A 矩阵快速幂
    hdu2604 Queuing
    支付宝 生活号 获取 userId 和 生活号支付
    maven 项目使用本地jar
    nexus 私有 maven 仓库的搭建
    linux jdk 安装
    gitlab 可以上传代码,但是 不能 上传 tag 问题
    maven 内置变量
    mysql 不允许分组的问题 this is incompatible with sql_mode=only_full_group_by
  • 原文地址:https://www.cnblogs.com/zhihang/p/11280024.html
Copyright © 2011-2022 走看看