C # simple general cache implementation
Some memory caches are often used in the program. Each acquired data needs to be cached again. The code is redundant. Based on this, a common memory cache is provided, directly run the Code:
/// <Summary>
/// Obtain the cache object
/// </Summary>
/// <Typeparam name = "T"> cache object </typeparam>
/// <Param name = "dele"> Object Data Acquisition Method </param>
/// <Param name = "cacheKey"> cache keyword </param>
/// <Param name = "cacheDuration"> cache time (minutes) </param>
/// <Param name = "objs"> get object parameters </param>
/// <Returns> parameter T </returns>
Public static T GetCacheData <T> (Delegate dele, string cacheKey, int cacheDuration, params ob ject [] objs)
{
If (HttpRuntime. Cache. Get (cacheKey) = null)
{
String assemblyName = dele. Target. GetType (). Assembly. FullName;
String typeName = dele. Target. GetType (). FullName;
Ob ject instance = Assembly. Load (assemblyName). CreateInstance (typeName );
MethodInfo methodInfo = dele. Method;
T result = (T) methodInfo. Invoke (instance, objs );
HttpRuntime. Cache. Add (cacheKey, result, null, Cache. NoAbsoluteExpiration, TimeSpan. FromMinutes (cacheDuration), CacheItemPriority. NotRemovable, null );
}
Return (T) HttpRuntime. Cache [cacheKey];
}
Use HttpRuntime. Cache to Cache data. If the cached data does not exist, use the delegate and reflection to call the business method to obtain and Cache the data. Use:
String result = CacheHelper. GetCacheData <string> (new Func <string, string> (cacheTest. GetMyData), "one", 5, "test ");
Include another version that may be reloaded:
Public static TResult GetCacheData <T1, T2, TResult> (Func <T1, T2, TResult> func, string cacheKey, int cacheTime, T1 para1, T2 para2)
{
If (HttpRuntime. Cache. Get (cacheKey) = null)
{
Console. WriteLine ("cache not hit ");
TResult result = func (para1, para2 );
HttpRuntime. Cache. Add (cacheKey, result, null, Cache. NoAbsoluteExpiration, TimeSpan. FromMinutes (cacheTime), CacheItemPriority. NotRemovable, null );
Return result;
}
Console. WriteLine ("hit cache ");
Return (TResult) HttpRuntime. Cache. Get (cacheKey );
}