add to Cache[Key]=object  or Cache.Insert

remove Cache.Remove(key)

1、 Write the value directly to Cache

The code is as follows Copy code
HttpContext.Current.Cache["One"] = "1";

Use ' Absolute Expiration ' How to handle cache , The expiration date is :9999 year 12 month 31 Japan ( This method is not recommended for caching , And the cache should be cleared at an appropriate time Key)

2、 Use Insert(String, Object) Insert Cache

The code is as follows Copy code
string cacheKey = "Two";
object cacheValue = HttpContext.Current.Cache.Get(cacheKey);

if(cacheValue == null)
    cacheValue = WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;

HttpContext.Current.Cache.Insert(cacheKey, cacheValue);

// Displays the... Of the specified cache Key And Value
this.ShowMessage(cacheKey, cacheValue.ToString());

3、 Use Insert(String, Object, CacheDependency, DateTime, TimeSpan) Insert Cache

The code is as follows Copy code
string cacheKey = "__cache__students";

DataSet dataSet = this.Cache.Get(cacheKey) as DataSet;

if(dataSet == null)
    dataSet = new DataSet();

// load XML And fill in DataSet

// Join the cache , And set ' Absolute expiration time ' by 5 minute
    this.Cache.Insert(cacheKey, dataSet, null, DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);

// binding DataGrid data
grdDefault.DataSource = dataSet;

The two important parameters of this method are as follows absoluteExpiration And slidingExpiration
absoluteExpiration  DateTime type , Represents the absolute expiration time
slidingExpiration  TimeSpan type , Represents the sliding expiration time
absoluteExpiration And slidingExpiration Can't be used at the same time
for example : Set the absoluteExpiration When parameters are ,slidingExpiration Must be set to System.Web.Caching.Cache.NoSlidingExpiration
conversely : Set the slidingExpiration When parameters are ,absoluteExpiration Must be set to System.Web.Caching.Cache.NoAbsoluteExpiration

4、 Use Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority,

For more details, please check :

CacheItemRemovedCallback) Insert Cache

public partial class PriorityAndCallbackDemo : System.Web.UI.Page
    #region Static field
    static bool CacheItemRemoved = false;
    static CacheItemRemovedReason Reason;
    static string CacheItemKey = "fw__cache__students";

#region Event handling
    // Page loading
    protected void Page_Load(object sender, EventArgs e)
        // Cache entry removed
            ltMessage.Text = string.Format("Key={0} Removed from cache , The reason is :{1}", PriorityAndCallbackDemo.CacheItemKey, PriorityAndCallbackDemo.Reason.ToString());

//' Add cache ' Button Click event Handle
    protected void btnAddCache_Click(object sender, EventArgs e)
        DataSet dataSet = this.Cache.Get(PriorityAndCallbackDemo.CacheItemKey) as DataSet;

if(dataSet == null)
            dataSet = new DataSet();

// Use Web.config As a cache expiration dependency
            CacheDependency dependency = new CacheDependency(this.Server.MapPath(@"Web.config"), DateTime.Now);

// Join the cache , Set the priority to the default level
            this.Cache.Insert(PriorityAndCallbackDemo.CacheItemKey, dataSet, dependency, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, new CacheItemRemovedCallback(this.CacheItemRemovedHandler));

// binding GridView data
        grdDefault.DataSource = dataSet;

//' Remove the cache ' Button Click event Handle
    protected void btnRemoveCache_Click(object sender, EventArgs e)
        if(this.Cache[PriorityAndCallbackDemo.CacheItemKey] != null)

#region Private method
    // Cache item removal event handling
    private void CacheItemRemovedHandler(string key, object value, CacheItemRemovedReason relason)
        PriorityAndCallbackDemo.CacheItemRemoved = true;
        PriorityAndCallbackDemo.Reason = relason;

The two important parameters of this method are as follows CacheItemPriority And CacheItemRemovedCallback
CacheItemPriority  Cache item priority , When the server is out of memory , The higher the priority, the less easy it is to remove
CacheItemRemovedCallback  This parameter is the delegate type , Called when the cache item is removed , contain Reason Parameter is used to indicate why the cache item is removed

【 How I use it 】

First, understand the caching strategy . Adjustable expiration policy and Absolute expiration policy . Be careful , Both cannot be used at the same time

Use an adjustable expiration policy , Need to put absoluteExpiration=DateTime.MaxValue ,TimeSpan .FromMinutes(10) Set items only in 10 It will only be removed if it is not used within minutes

The code is as follows Copy code
Cache.Insert("data", "123", null , DateTime.MaxValue, TimeSpan.FromMinutes(10));

Absolute strategy , Such as the weather report , Save the information 60 minute

The code is as follows Copy code
Cache.Insert("data", "123", null , DateTime.Now.AddMinutes(60), TimeSpan.Zero);

Cache dependency .

That is, the failure of one cache depends on another object. there object You can refer to another cache , Or a file , perhaps ....

class :CacheDependency Namespace System.Web.Caching.CacheDependency Depending on other cache items

The code is as follows Copy code
System.Web.Caching.CacheDependency cacheDependency = new System.Web.Caching.CacheDependency (null, new string [] { "time" });
Cache.Insert( "number", ++num, cacheDependency);
Depending on a file or folder
System.Web.Caching. CacheDependency cacheDependency = new System.Web.Caching.CacheDependency ( "test.xml");
When test.xml File deletion 、 Automatically remove from cache when updating
System.Web.Caching.CacheDependency cacheDependency = new System.Web.Caching.CacheDependency(null, new string[] { "time" });
Cache.Insert("test", "123", cacheDependency);

Remove item callback
 Cache.Insert("test", "123", null , DateTime.Now.AddSeconds(10), TimeSpan.Zero, new CacheItemUpdateCallback(Test));
 private void Test(string key, CacheItemUpdateReason reason, out object expensiveObject, out CacheDependency dependency, out DateTime absoluteExpiration, out TimeSpan slidingExpiration)

ASP.NET cache Cache More articles on data caching

  1. MVC-Cache-1. Output buffer (Cache:[1]. Output buffer 2. Application caching )

    Cache premise concept : 1. The purpose of using caching is to provide website performance , Reduce the pressure on the database , Speed up access . 2. If the cache is not used properly , The impact is worse than not using caching ( The cache data is not updated in time . Too much cache, etc ). MV ...

  2. I use ASP.NET Cache of SQL Data caching depends on (SqlCacheDependency)

    [ A term is used to explain ] cache (Cache) rely on , The vernacular explanation is that whether the cache is updated depends on others Object. that SqlCacheDependency Refers to Cache The data update of depends on SQL Server Changes in database tables (  ...

  3. [.net Advanced object oriented programming ] (15) cache (Cache)( Two ) Using cache to improve program performance

    [.net  Advanced object oriented programming ] (15)  cache (Cache)( Two )  Using cache to improve program performance This section is a guide to : The last section said that caching is a technology of exchanging space for time , This paper introduces the client cache and two kinds of server cache , This section mainly introduces a . ...

  4. [.net Advanced object oriented programming ] (14) cache (Cache) ( One ) Learn about caching technology

    [.net  Advanced object oriented programming ] (14)  cache (Cache)( One )  Learn about caching technology This section is a guide to : cache (Cache) It's a technology that trades space for time , stay .NET Reasonable use in programming , Can greatly improve the efficiency of the program ...

  5. web What developers should know web Cache knowledge – Cache data to browser side Net Realization

    In reality , The server is sending data to the browser , Part of the data is not updated very often , If you can cache this part of data to the browser , It will greatly reduce the amount of data transmitted , Improve application performance . adopt Expires Strategy , have access to HTTP The caching mechanism defined by the protocol will ...

  6. cache application ( 2.0 SQL Data caching depends on [SqlCacheDependency ] ) 2.0 Provides a new data caching function , Is the use sql server2005 The asynchronous notification function is used to implement caching 1. First, in the sqlserver2005 Create a test The database of . stay SQL Ser ...

  7. mybatis Source code analysis (7)----- cache Cache( First level cache , Second level cache )

    Write it at the front  MyBatis Provide query caching , Used to reduce database pressure , Improve database performance . MyBatis Cache is divided into first level cache and second level cache . By means of Executor The design of the . It can also be found MyBatis Cache mechanism ( Use a mold ...

  8. MVC-Cache-2. Application caching (Cache:1. Output buffer [2]. Application caching )

    2. Application data caching -Cache 1. introduce CacheHelper.cs CacheHelper.cs The source code of the file is below ; 2. Introduce the usage : // key string ips = " key "; // value ...

  9. echarts Graphics report cache problem (option Data caching )

    I use it in my work these days echarts Developing reports . Every time the data is new , however echart The graphic report is the same as the previous data . I searched the Internet many times, but I couldn't solve it , After that, we added technology group to solve it . I've decided at first that it's a report ...

Random recommendation

  1. MC The implementation of distributed algorithm and some summary

    First we know that Memcached It's a distributed caching system , but memcached It's not like mongodb like that , Allows multiple nodes to be configured , And data is automatically allocated between nodes in other words memcached Between nodes , They don't communicate with each other , ...

  2. Recently used JQuery Easyui A couple of strange questions I met

    Recent projects want to try Easyui To do the front-end interface , But there were a few problems in the beginning , recorded , So as not to forget . 1. After clicking the add or Modify button , Pop up form , Form content participates in “href” Property remote load problem : The first pop-up is normal , But again ...

  3. git relevant

    Enter into the world where you want to use git Managed project Under the table of contents 1.git init This means that the directory will be git Watch everything change Generate a .git The folder contains the management information project All the necessary information 2.git add &l ...

  4. jiffies

    linux Medium jiffies Variable Global variables jiffies It is used to record the total number of beats produced since the system started up . Startup time , The kernel initializes the variable to 0, thereafter , Each time the clock interrupt handler increases the value of the variable . The number of clock interrupts per second is equal to H ...

  5. stay Action China and Israel Struts2 Mode output of JSON data

    Reference address ;

  6. Android Studio Use OpenCV after , send APP Not to install OpenCV Manager You can run

    Reprinted from Using static initialization , You can click the link below to see the official document introduction ...

  7. UVa 1328 (KMP Find the period of the string ) Period

    When beginners learn KMP I also did this problem when I was young , Now it seems that Liu Rujia's code should be simplified , After all, the shorter the code, the better to remember , The less error prone . and KMP The code style of the recursive mismatch function and the following Aho-Corasick The code style of automata for mismatch function is also ...

  8. 6.2、Android Studio Memory

    Android Monitor Provides a Memory Monitor, So you can easily monitor application performance and memory usage , You can find useless objects , Local memory leaks and memory usage of connected devices .Memory Monitor Show ...

  9. .net Reply to picture

    using System;using System.Collections.Generic;using System.Web;using System.Web.UI;using System.Web. ...

  10. LGP2801 The Lord's magic

    Topic link : P2801 The Lord's magic This is the first time A It's a block problem That's the template question Sort within each block Each block only needs to maintain the modification amount of the whole block Query operation : For edge blocks Direct violence is found in [l, r] Inside And there are several larger than the given value For the whole piece ...