ASP.NET WebForms缓存非常方便地用于临时保留操作数据。在.NET平台的早期,即使在Winforms应用程序中,开发人员也经常使用System.Web名称空间。
关于ASP.NET缓存文章中不断提供的代码模板非常简单且实用:
// try to get an instance of object from cache
DataSet ds = HttpRuntime . Cache [ "KeyName" ] as DataSet ;
// check the result and recreate it, if it is null
if ( ds == null )
{
ds = QueryDataFromDatabase ( ) ;
HttpRuntime . Cache . Insert ( "KeyName" , ds ) ;
}
// using the instance of object that has been populated from cache or from storage
DataRow dr = ds . Tables [ 0 ] . Rows [ 0 ] ;但是,ASP.NET缓存实现不包括一些理想的功能。
尽管在缓存中添加值的CACH.INSERT(字符串,对象)方法适用于大多数情况,但通常需要根据Web.config文件中存储的Web应用程序的设置为缓存数据进行不同的设置,有时甚至完全将缓存功能完全禁用于整个应用程序。在这种情况下,不应更改源代码,并且在不重新编译的情况下运行应用程序。
无论该实例的实际类型是什么,ASP.NET缓存总是返回object类的实例。在大多数情况下,这不是问题,因为可以使用Nullable types代替Value types 。也许您想拥有从缓存中检索数据的通用方法:
// this is a dafault extraction data from cache
myClassName item = HttpRuntime . Cache [ "Key1" ] as myClassName ;
// this is a desired extraction data with generic methods
myClassName item = DataCache . Get < myClassName > ( "Key1" ) ; 如果不满足您的通用方法,则可以使用默认版本。实际上,这两个选择是相同的。但是通用方法提供了其他功能。例如,如果缓存不包含要检索的值,则可以定义默认值:
myClassName defaultValue = new myClassName ( /* init properties */ ) ;
myClassName item = DataCache . Get < myClassName > ( "Key1" , defaultValue ) ;
/* if there is nothing in the cache, then the item will be defaultValue */ASP.NET缓存总是返回存储在缓存中的对象。这意味着更改提取的对象的任何属性也将更改存储在缓存中的对象,因为这些对象是相同的对象。在某些情况下,您可能需要修改检索到的对象,但将对象留在缓存中。方便的功能之一是从高速缓存中检索对象的副本,该副本可以更改,而不必担心缓存中的对象。
ASP.NET缓存类似于NameValueCollection 。对于小型Web应用程序来说,这是简单而优雅的解决方案,但是当应用程序长大时,很难生成钥匙。例如,考虑缓存两个相关表,例如供应商和模型。在这种情况下,Web应用程序将在一个缓存的对象中将所有数据保留在供应商表中,以及许多缓存对象,用于模型表的关联记录。供应商的钥匙应该是Vendors ,而应该是Models.[VendorID] 。当供应商表已更改后,供应商的缓存实例,仅需从缓存中删除模型的相关实例。这意味着应通过区域将数据缓存并从缓存中删除。
所述功能是可选的,可以在任何Web应用程序中轻松实现。代理模板是实现所有描述的功能的好选择。所得的库可用于所有.NET框架,即启动版2.0。 .NET Framework 4.0介绍了System.Runtime.Caching名称空间和具有新的缓存模型的几个类。因此,不需要使用标准ASP.NET缓存及其改进。
悲伤但真实。
/// <summary>
/// Is cache used or not
/// </summary>
public static bool IsCacheEnable ;
/// <summary>
/// How to store objects in the cache
/// </summary>
public static CacheExpirationType ExpirationType ;
/// <summary>
/// How long objects should be stored in the cache
/// </summary>
public static TimeSpan ExpirationTime ;枚举CacheExpirationType定义了如何将对象存储在缓存中
/// <summary>
/// How to store objects in the cache
/// </summary>
public enum CacheExpirationType
{
/// <summary>
/// Without time limit, the value of the <seealso cref = "DataCache.ExpirationTime" /> property will be ignored
/// </summary>
NoExpiration ,
/// <summary>
/// The <seealso cref="DataCache.ExpirationTime"/> at which the inserted object expires and is removed from the cache
/// </summary>
AbsoluteExpiration ,
/// <summary>
/// The interval <seealso cref="DataCache.ExpirationTime"/> between the time the inserted object is last accessed and the time at which that object expires
/// </summary>
SlidingExpiration
} /// <summary>
/// Retrieves the specified item from the Cache object
/// </summary>
/// <typeparam name="T">The type for the cache item to retrieve</typeparam>
/// <param name="key">The identifier for the cache item to retrieve</param>
/// <param name="defaultValue">The default value if the object is not in the cache</param>
/// <returns>The retrieved cache item, or <paramref name="defaultValue"/> if the key is not found</returns>
public static T GetData < T > ( string key , T defaultValue = default ( T ) )
/// <summary>
/// Retrieves the deep copied of specified item from the Cache object
/// </summary>
/// <typeparam name="T">The type for the cache item to retrieve</typeparam>
/// <param name="key">The identifier for the cache item to retrieve</param>
/// <param name="defaultValue">The default value if the object is not in the cache</param>
/// <returns>The retrieved cache item, or <paramref name="defaultValue"/> if the key is not found</returns>
public static T GetDeepCopiedData < T > ( string key , T defaultValue = default ( T ) ) /// <summary>
/// Inserts an item into the cache with a cache key to reference its location, using default values provided by the settings
/// </summary>
/// <param name="key">The cache key used to reference the item</param>
/// <param name="value">The object to be inserted into the cache</param>
public static void InsertData ( string key , object value )
/// <summary>
/// Inserts an item into the cache with a cache key to reference its location, using the absolute expiration time
/// </summary>
/// <param name="key">The cache key used to reference the item</param>
/// <param name="value">The object to be inserted into the cache</param>
/// <param name="expirationTime">How long the object should be stored in the cache</param>
public static void InsertAbsoluteExpirationData ( string key , object value , TimeSpan expirationTime )
/// <summary>
/// Inserts an item into the cache with a cache key to reference its location, using the sliding expiration time
/// </summary>
/// <param name="key">The cache key used to reference the item</param>
/// <param name="value">The object to be inserted into the cache</param>
/// <param name="expirationTime">How long the object should be stored in the cache</param>
public static void InsertSlidingExpirationData ( string key , object value , TimeSpan expirationTime )
/// <summary>
/// Inserts an item into the cache with a cache key to reference its location, using the type of expiration and default value for expiration time
/// </summary>
/// <param name="key">The cache key used to reference the item</param>
/// <param name="value">The object to be inserted into the cache</param>
/// <param name="expirationType">How to store objects in the cache</param>
public static void InsertExpirationData ( string key , object value , CacheExpirationType expirationType )
/// <summary>
/// Inserts an item into the cache with a cache key to reference its location, using the type of expiration and expiration time
/// </summary>
/// <param name="key">The cache key used to reference the item</param>
/// <param name="value">The object to be inserted into the cache</param>
/// <param name="expirationType">How to store objects in the cache</param>
/// <param name="expirationTime">How long the object should be stored in the cache</param>
public static void InsertExpirationData ( string key , object value , CacheExpirationType expirationType , TimeSpan expirationTime ) /// <summary>
/// Removes the specified item from the application's cache
/// </summary>
/// <param name="key">An identifier for the cache item to remove</param>
public static void RemoveDataByKey ( string key )
/// <summary>
/// Removes all items from the application's cache that starts with key
/// </summary>
/// <param name="keyStartsWith">An starts with identifier for the cache item to remove</param>
public static void RemoveAllDataByKey ( string keyStartsWith )
/// <summary>
/// Removes all items from the application's cache
/// </summary>
public static void RemoveAllData ( ) public class Global : System . Web . HttpApplication
{
protected void Application_Start ( object sender , EventArgs e )
{
Settings settings = Settings . Default ;
DataCache . IsCacheEnable = settings . IsCacheEnable ;
DataCache . ExpirationType = settings . ExpirationType ;
DataCache . ExpirationTime = settings . ExpirationTime ;
}
} public partial class DefaultPage : System . Web . UI . Page
{
public const string STR_CACHENAME = "something" ;
protected void Page_Load ( object sender , EventArgs e )
{
if ( ! this . IsPostBack )
{
SomethingDataModel val = DataCache . GetData < SomethingDataModel > ( STR_CACHENAME ) ;
if ( val == null )
{
SomethingDataModel val = new SomethingDataModel ( ) ; // get data from ...
DataCache . InsertData ( STR_CACHENAME , val ) ;
}
DataBind ( val ) ; // use data on the page
}
}
}如果要定义与默认情况下指定的时间设置不同的时间设置,请使用覆盖的Insert{Which}Data方法之一。
public partial class DefaultPage : System . Web . UI . Page
{
public const string STR_CACHENAME = "something" ;
protected void Page_Load ( object sender , EventArgs e )
{
if ( this . IsPostBack )
{
DAL . Update ( ) ; // update the database ...
DataCache . RemoveAllDataByKey ( STR_CACHENAME ) ; // clear cache
Response . Redirect ( "Default.aspx" ) ; // proccessing the request
}
}
} 有疑问?与我联系,我将帮助您解决。
<style> .inner {min宽度:800px!最大宽度:60%!重要;} </style>