zoukankan      html  css  js  c++  java
  • .NET 4.0中的缓存功能

    # .NET 4.0中的缓存功能


    .Net 4.0中有3种,System.Runtime.Caching,System.Web.Caching.Cache,
    Output.Cache。下面分别对这三者进行介绍:

    ### 应用程序缓存 System.Runtime.Caching
    -----------------------------
    .net4内置的高速缓存
    ```
    private void button1_Click(object sender, EventArgs e)
    {
    ObjectCache objectCache = MemoryCache.Default;

    string value1 = objectCache["key1"] as string;

    CacheItemPolicy policy = new CacheItemPolicy();

    //--------------设置过期时间----------------
    policy.AbsoluteExpiration = DateTime.Now.AddHours(1);

    objectCache.Set("key1", "11223366", policy);

    value1 = objectCache["key1"] as string;

    //---------------测试不同类型时 as 是否能自动转换---------
    objectCache.Set("key1", 112233, policy);

    value1 = objectCache["key1"] as string;


    //---------------测试Add方法,在键已经存在的情况下会不会报错------
    bool b = objectCache.Add("key1", 112233, policy);

    //---------------测试Add方法,键不存在的情况------
    b = objectCache.Add("key2", 445566, policy);

    int n = (int)objectCache.Get("key2") ;
    }
    ```

    ### Web应用程序缓存 System.Web.Caching.Cache
    -----------------------------
    Web程序的缓存,Asp.Net MVC4中使用ViewBag来传递参数。

    ```
    public ActionResult CacheTest()
    {
    ViewBag.Message = "Web缓存";

    Cache cache = HttpRuntime.Cache;

    if (cache["Key1"] == null)
    {
    cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(600), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove);
    }
    `
    string s = cache["Key1"] as string;
    ViewBag.Key1 = s;
    ViewBag.Setting = "配置啊";

    return View();
    }

    //-----------------Razor页面使用-------------------
    @ViewBag.Key1
    ```


    ### 页面输出缓存 Output.Cache
    -----------------------------
    页面输出缓冲,Output.Cache是MVC的一个注解[Output.Cache]。
    在过期时间内,返回给浏览器304,表示页面内容未修改。
    ```
    [OutputCache(Duration =20)]//设置过期时间为20秒
    public ActionResult ExampleCache()
    {
    var timeStr =DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分ss秒");
    ViewBag.timeStr = timeStr;
    return View();
    }
    ```

  • 相关阅读:
    QT visual stuido 集成插件不能打开ui文件的原因
    KLSudoku 1.2 数独游戏软件发布
    QT for linux 的错误 undefined reference to 'FcFreeTypeQueryFace' 的解决方法
    tp3.2源码解析——入口文件
    关于php调用.net的web service 踩过的坑
    CentOS7 LNMP+phpmyadmin环境搭建(二、LNMP环境搭建)
    CentOS7 LNMP+phpmyadmin环境搭建(一、虚拟机及centos7安装)
    php无限分类
    php的文件引用
    CentOS7 LNMP+phpmyadmin环境搭建(三、安装phpmyadmin)
  • 原文地址:https://www.cnblogs.com/jiftle/p/7760363.html
Copyright © 2011-2022 走看看