Application Data Cache
This cache depends on the system. Web. caching namespace.
This namespace provides common data classes on the cache server. A cache class contains many methods. Because this class is a dictionary class, store any data objects, such as hash tables and datasets. These methods can add, delete, or invalidate these objects, and even depend on objects of other files or cache items, in addition, callback can be executed when an object is removed from the cache to notify the application. The sample code is as follows:
Application Data Cache
1 // Add a namespace
2 using system. Web. caching;
3
4 /// <summary>
5 // obtain the object from the cache based on the index key value
6 /// </Summary>
7 // <Param name = "cachekey"> index key value </param>
8 /// <returns> cached object </returns>
9 private static object getobjectfromcache (string cachekey)
10 {
11 cache = httpruntime. cache;
12 Return cache [cachekey];
13}
14
15 /// <summary>
16 // Add the object to the cache with cachekey as the index key value
17 /// </Summary>
18 /// <Param name = "cachekey"> index key value </param>
19 /// <Param name = "OBJ"> object to be cached </param>
20 private static void addobjecttocache (string cachekey, object OBJ)
21 {
22 cache = httpruntime. cache;
23 cache. insert (cachekey, OBJ );
24}
25
26 /// <summary>
27 // Add the object to the cache with cachekey as the index key value
28 /// </Summary>
29 // <Param name = "cachekey"> index key value </param>
30 /// <Param name = "OBJ"> object to be cached </param>
31 // <Param name = "absoluteexpiration"> absolute expiration time </param>
32 // <Param name = "slidingexpiration"> interval between the last time the inserted object is accessed and when the object expires </param>
33 Private Static void addobjecttocache (string cachekey, object OBJ, datetime absoluteexpiration, timespan slidingexpiration)
34 {
35 cache = httpruntime. cache;
36 cache. insert (cachekey, OBJ, null, absoluteexpiration, slidingexpiration );
37}
38
39 protected void page_load (Object sender, eventargs E)
40 {
41 string cachekey = "_ test ";
42
43 // get from Cache
44 object OBJ = getobjectfromcache (cachekey );
45 // No
46 If (OBJ = NULL)
47 {
48 // cache the current time
49 OBJ = datetime. now;
50 if (OBJ! = NULL)
51 {
52 // cache time 30 seconds
53 int cachetime = 30;
54 // Add it to the cache
55 addobjecttocache (cachekey, OBJ, datetime. Now. addseconds (cachetime), timespan. Zero );
56}
57}
58 literal1.text = obj. tostring ();
59}
These codes are good cache solutions, but there is a problem here. When the data changes, the cache still contains expired data, only after the cache content expires, to obtain new data. The following two articles solve this problem.