Using System; Using System. Collections. Generic; Using System. IO; Using System. Linq; Using System. Runtime. Serialization. Formatters. Binary; Using System. Timers; Using System. Web. Caching; Using System. Collections. Concurrent; Namespace _ 19_1 { Public class MyOutputCacheProvider: OutputCacheProvider { Private Timer timer; Private string cachePath = "C: \ Cache \"; Private ConcurrentDictionary <string, DateTime> CacheExpireList; Private const string KEY_PREFIX = "_ outputCache _"; Public MyOutputCacheProvider () { CacheExpireList = New ConcurrentDictionary <string, DateTime> (); Timer = new Timer (3000 ); Timer. Elapsed + = (o, e) => { Var discardedList = from cacheItem in cacheExpireList Where cacheItem. Value <DateTime. Now Select cacheItem; Foreach (var discarded in discardedList) { Remove (discarded. Key ); DateTime discardedDate; CacheExpireList. TryRemove (discarded. Key, Out discardedDate ); } }; Timer. Start (); } /// <Summary> /// Add cache /// </Summary> /// <Param name = "key"> cache key </param> /// <Param name = "entry"> cached object </param> /// <Param name = "utcExpiry"> expiration time </param> /// <Returns> return cache value </returns> Public override object Add (string key, object entry, DateTime utcExpiry) { FileStream fs = new FileStream ( String. Format ("{0} {1}. binary", cachePath, key ), FileMode. Create, FileAccess. Write ); BinaryFormatter formatter = new BinaryFormatter (); Formatter. Serialize (fs, entry ); Fs. Close (); CacheExpireList. TryAdd (key, utcExpiry. ToLocalTime ()); Return entry; } /// <Summary> /// Obtain the cache value /// </Summary> /// <Param name = "key"> cache key </param> /// <Returns> cache value </returns> Public override object Get (string key) { String path = String. Format ("{0} {1}. binary", cachePath, key ); If (File. Exists (path )) { FileStream fs = new FileStream ( Path, FileMode. Open, FileAccess. Read ); BinaryFormatter formatter = new BinaryFormatter (); Object result = formatter. Deserialize (fs ); Fs. Close (); Return result; } Else { Return null; } } /// <Summary> /// Remove the cache based on the key /// </Summary> /// <Param name = "key"> cache key </param> Public override void Remove (string key) { String path = String. Format ("{0} {1}. binary", cachePath, key ); If (File. Exists (path )) { File. Delete (path ); } } /// <Summary> /// Set cache /// </Summary> /// <Param name = "key"> cache key </param> /// <Param name = "entry"> cached object </param> /// <Param name = "utcExpiry"> expiration time </param> Public override void Set (string key, object entry, DateTime utcExpiry) { String path = String. Format ("{0} {1}. binary", cachePath, key ); FileStream fs = new FileStream ( Path, FileMode. Create, FileAccess. Write ); BinaryFormatter formatter = new BinaryFormatter (); Formatter. Serialize (fs, entry ); Fs. Close (); CacheExpireList. TryAdd (key, utcExpiry. ToLocalTime ()); } } } |