c# 缓存!
做项目的时候获取所有城市的时候,发现每次去获取都花费了很多时间,所以用缓存方法让效率更高!
这是我做的例子,如下:
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;
}
}