O cache do WebForms do ASP.NET foi implementado de maneira muito conveniente para manter temporários para manter os dados operacionais. Nos primeiros anos da plataforma .NET, os desenvolvedores costumavam trabalhar com System.Web Namespace, mesmo em aplicativos Winforms.
O modelo de código, que está sendo constantemente oferecido em artigos sobre o cache do ASP.NET, é muito simples e prático:
// 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 ] ;No entanto, a implementação do cache do ASP.NET não inclui alguns recursos desejáveis.
Embora o método Cache.Insert (String, Object), que agregue um valor ao cache, seja adequado para a maioria dos casos, geralmente é desejável apresentar diferentes configurações para armazenamento de dados com base nas configurações do aplicativo da Web armazenadas no arquivo web.config e, às vezes, até mesmo desativando completamente o cache para todo o aplicativo. Nesse caso, o código -fonte não deve ser alterado e o aplicativo deve ser executado sem recompilar.
O cache ASP.NET sempre retorna instâncias da classe object , independentemente do tipo real da instância. Na maioria dos casos, isso não é um problema, porque os Nullable types podem ser usados em vez dos Value types . Talvez você queira ter métodos genéricos para recuperar dados do cache:
// 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" ) ; Se os métodos genéricos não estiverem satisfeitos para você, será possível usar a versão padrão. De fato, essas duas opções são idênticas. Mas os métodos genéricos oferecem recursos adicionais. Por exemplo, o valor padrão pode ser definido se o cache não contiver um valor a ser recuperado:
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 */O cache asp.net sempre retorna o objeto armazenado no cache. Isso significa que as alterações em qualquer propriedade do objeto extraído também alterarão o objeto armazenado no cache, pois esses são os mesmos objetos. Em alguns casos, você pode modificar o objeto recuperado, mas deixe o objeto no cache inalterado. Uma das funcionalidades convenientes é recuperar uma cópia de um objeto do cache que pode ser alterado sem se preocupar com o objeto no cache.
O cache ASP.NET é semelhante a uma NameValueCollection . É uma solução simples e elegante para um pequeno aplicativo da Web, mas fica difícil gerar as chaves quando o aplicativo crescer. Por exemplo, considere o armazenamento em cache duas tabelas relacionadas, como fornecedores e modelos. Nesse caso, o aplicativo da Web manterá todos os dados da tabela de fornecedores em um objeto em cache e muitos objetos em cache para registros associados da tabela de modelos. A chave para os fornecedores deveriam ser Vendors e as chaves para modelos que devem ser Models.[VendorID] . Quando a tabela de fornecedores foi alterada, a instância em cache para fornecedores e apenas instâncias associadas para modelos devem ser removidas do cache. Isso significa que os dados devem ser armazenados em cache e removidos do cache por regiões.
As funções descritas são opcionais e podem ser facilmente implementadas em qualquer aplicativo da Web. O modelo de proxy é uma boa opção para implementar todos os recursos descritos. A biblioteca resultante pode ser usada em todas as estruturas .NET, a versão 2.0 inicial. O .NET Framework 4.0 apresenta o espaço de nome System.Runtime.Caching e várias classes com um novo modelo de armazenamento em cache. Portanto, o uso do cache ASP.NET padrão e suas melhorias não é necessário.
Triste, mas verdade.
/// <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 ; Enum CacheExpirationType define como armazenar objetos no cache
/// <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
}
}
} Se você deseja definir configurações de tempo diferentes de especificadas por padrão no cache, use um dos métodos 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
}
}
} Tendo perguntas? Entre em contato comigo e eu o ajudarei a resolver isso.
<estilo> .inner {Min-Width: 800px! IMPORTANTE; Max-lar: 60%! IMPORTANTE;} </style>