前言
缓存主要是为了提高数据的读取速度。因为服务器和应用客户端之间存在着流量的瓶颈,所以读取大容量数据时,使用缓存来直接为客户端服务,可以减少客户端与服务器端的数据交互,从而大大提高程序的性能。
缓存这个东西可大可小,小到一个静态的字段,大到将整个数据库Cache起来。项目开发过程中缓存的应用到处可见,本文主要介绍一下使用的方法,下面话不多说了,来一起看看详细的介绍吧
1.在ASP.NET中页面缓存的使用方法简单,只需要在aspx页的顶部加上一句声明即可:
<%@ OutputCache Duration="100" VaryByParam="none" %>
Duration:缓存时间(秒为单位),必填属性
2.使用微软自带的类库System.Web.Caching
新手接触的话不建议直接使用微软提供的类库,因为这样对理解不够深刻。所以在这里我带大家自己写一套缓存操作方法,这样理解得更加清晰。
话不多说,代码开敲。
一、首先,先模拟数据来源。新建一个类,写一个数据操作方法(该方法耗时、耗资源)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Cache
{
public class DataSource
{
/// <summary>
/// 模拟从数据库读取数据
/// 耗时、耗CPU
/// </summary>
/// <param name="count"></param>
public static int GetDataByDB(int count)
{
Console.WriteLine("-------GetDataByDB-------");
int result = 0;
for (int i = count; i < 99999999; i++)
{
result += i;
}
Thread.Sleep(2000);
return result;
}
}
}










