这篇文章主要介绍了C# Cache缓存读取的设置方法,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下
先创建一个CacheHelper.cs类,代码如下:
using System;
using System.Web;
using System.Collections;
using System.Web.Caching;
public class CacheHelper
{
/// <summary>
/// 获取数据缓存
/// </summary>
/// <param name="cacheKey">键</param>
public static object GetCache(string cacheKey)
{
var objCache = HttpRuntime.Cache.Get(cacheKey);
return objCache;
}
/// <summary>
/// 设置数据缓存
/// </summary>
public static void SetCache(string cacheKey, object objObject)
{
var objCache = HttpRuntime.Cache;
objCache.Insert(cacheKey, objObject);
}
/// <summary>
/// 设置数据缓存
/// </summary>
public static void SetCache(string cacheKey, object objObject, int timeout = 7200)
{
try
{
if (objObject == null) return;
var objCache = HttpRuntime.Cache;
//相对过期
//objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);
//绝对过期时间
objCache.Insert(cacheKey, objObject, null, DateTime.Now.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null);
}
catch (Exception)
{
//throw;
}
}
/// <summary>
/// 移除指定数据缓存
/// </summary>
public static void RemoveAllCache(string cacheKey)
{
var cache = HttpRuntime.Cache;
cache.Remove(cacheKey);
}
/// <summary>
/// 移除全部缓存
/// </summary>
public static void RemoveAllCache()
{
var cache = HttpRuntime.Cache;
var cacheEnum = cache.GetEnumerator();
while (cacheEnum.MoveNext())
{
cache.Remove(cacheEnum.Key.ToString());
}
}
}
然后是调用:
public IEnumerable<CompanyModel> FindCompanys()
{
var cache = CacheHelper.GetCache("commonData_Company");//先读取
if (cache == null)//如果没有该缓存
{
var queryCompany = _base.CompanyModel();//从数据库取出
var enumerable = queryCompany.ToList();
CacheHelper.SetCache("commonData_Company", enumerable);//添加缓存
return enumerable;
}
var result = (List<CompanyModel>)cache;//有就直接返回该缓存
return result;
}
测试结果:
首次加载进来是为null,然后读取数据库,添加进缓存,当前返回前台的是从数据库中取出的数据。
刷新页面,发现缓存中已经有了读出的30条数据,
然后接下来走,返回缓存中的数据:
以上就是C# Cache缓存读取的设置方法的详细内容,更多关于C# Cache缓存读取的资料请关注得得之家其它相关文章!
织梦狗教程
本文标题为:C# Cache缓存读取的设置方法


基础教程推荐
猜你喜欢
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 如果条件可以为空 2022-01-01