C#中缓存的基本使用方法
实现目的:窗体打开时只访问一次数据库,将查询的结果存放在程序缓存中,此后员工每次操作时只与缓存做对比,不与数据库做对比,以此来减少数据库开销。
public partial class Form1 : Form { string result = ""; //定义一个全局接收变量 public Form1() { InitializeComponent(); GetCampusById(); textBox2.Text = Convert.ToString(DateTime.Now); } /// <summary> /// 调用sql查询数据 /// </summary> /// <returns></returns> public string GetCampusById() { string conn = ""; string sql = ""; using (SqlDataAdapter da = new SqlDataAdapter(sql, conn)) { DataSet ds = new DataSet(); da.Fill(ds); string FPlanNO = ds.Tables[0].Rows[0]["FPlanNO"].ToString(); string FMakeDate = ds.Tables[0].Rows[0]["FMakeDate"].ToString(); return FPlanNO; } } /// <summary> /// 写入缓存 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { string key = textBox4.Text; //key值 string value = Convert.ToString(DateTime.Now); //value值 //从缓存拿数据,但是每次得输入key和value result = cachehelper.getcache<string>(key, value); listBox1.Items.Add(key + " " + DateTime.Now); } /// <summary> /// 对比缓存 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { //每次拿输入的值和缓存做对比 string key = textBox3.Text; //key值 string value = Convert.ToString(textBox1.Text); //key值 //从缓存拿数据,但是每次得输入key和value result = cachehelper.getcache<string>(key, value); textBox5.Text = result; } }
再来一个缓存类
/// <summary> /// 缓存类 /// </summary> public class cachehelper { //缓存容器 private static Dictionary<string, object> cachedictionary = new Dictionary<string, object>(); /// <summary> /// 添加缓存 /// </summary> public static void add(string key, object value) { cachedictionary.Add(key, value); } /// <summary> /// 获取缓存 /// </summary> public static t get<t>(string key) { return (t)cachedictionary[key]; } /// <summary> /// 判断缓存是否存在 /// </summary> /// <param name="key"></param> /// <returns></returns> public static bool exsits(string key) { return cachedictionary.ContainsKey(key); } /// <summary> /// 缓存获取方法 /// </summary> /// <typeparam name="t"></typeparam> /// <param name="key">缓存字典容器对应key</param> /// <param name="func">委托方法 传入操作对象</param> /// <returns></returns> public static T getcache<T>(string key, object value) { if (cachehelper.exsits(key)) { //缓存存在,直接获取原数据 cachehelper.get<Object>(key); } else { //缓存不存在,去生成缓存,并加入容器 cachehelper.add(key, value); } return (T)cachehelper.get<Object>(key); } }
欧克,完事