码迷,mamicode.com
首页 > Windows程序 > 详细

c# 缓存!

时间:2016-03-24 14:44:32      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

做项目的时候获取所有城市的时候,发现每次去获取都花费了很多时间,所以用缓存方法让效率更高!

这是我做的例子,如下:

 

public class CacheGetCity

{

/// <summary>
/// 城市集合
/// </summary>
private static List<MCityInfo> allCityList;

/// <summary>
/// 最后访问时间
/// </summary>
private static DateTime lastTime;

/// <summary>
/// 获取全量城市对
/// </summary>
/// <returns>城市对</returns>
public static List<MCityInfo> GetInterCityList()
{
if (allCityList == null || allCityList.Count <= 0)
{
allCityList = GetAllCityInfo();
lastTime = DateTime.Now;
}

if (lastTime.AddHours(1) < DateTime.Now)////缓存一小时
{
allCityList = GetAllCityInfo();
lastTime = DateTime.Now;
}

return allCityList;
}

/// <summary>
/// 根据Code获取城市对
/// </summary>
/// <param name="code">城市编码</param>
/// <returns>城市对</returns>
public static string GetCityNameByCode(string code)
{
string cityName = string.Empty;
GetInterCityList();
List<MCityInfo> list = allCityList.FindAll(arg => arg.AirportCode == code);
foreach (var city in list)
{
cityName += city.CityName + "/";
}

cityName = cityName.TrimEnd(‘/‘);

return cityName;
}

/// <summary>
/// 根据城市名称获取三字码
/// </summary>
/// <param name="name">城市名称</param>
/// <returns>城市三字码</returns>
public static string GetCityCodeByName(string name)
{
string cityCode = string.Empty;
GetInterCityList();
List<MCityInfo> list = allCityList.FindAll(arg => arg.CityName == name);
foreach (var city in list)
{
cityCode += city.AirportCode + ",";
}

cityCode = cityCode.TrimEnd(‘,‘);
return cityCode;
}

/// <summary>
/// 获取城市信息全量
/// </summary>
/// <returns>城市信息</returns>
private static List<MCityInfo> GetAllCityInfo()
{
string notifyInfo = WcfCallHelper.Instance.Invoke<IFlightChangeDataService, string>("GetCitInfos");
List<MCityInfo> cityList = JsonConvert.DeserializeObject<List<MCityInfo>>(notifyInfo);
return cityList;
}

}

c# 缓存!

标签:

原文地址:http://www.cnblogs.com/skyfreedom/p/5315328.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!