.NET Framework Class Library Cache..::.Add Method Adds the specified item to the Cache object with dependencies, expiration and priority policies, and a delegate you can use to notify your application when the inserted item is removed from the Cache.
Namespace:
System.Web.Caching
Assembly:
System.Web (in System.Web.dll)

Syntax
Public Function Add ( _
key As String, _
value As Object, _
dependencies As CacheDependency, _
absoluteExpiration As DateTime, _
slidingExpiration As TimeSpan, _
priority As CacheItemPriority, _
onRemoveCallback As CacheItemRemovedCallback _
) As Object
public Object Add(
string key,
Object value,
CacheDependency dependencies,
DateTime absoluteExpiration,
TimeSpan slidingExpiration,
CacheItemPriority priority,
CacheItemRemovedCallback onRemoveCallback
)
public:
Object^ Add(
String^ key,
Object^ value,
CacheDependency^ dependencies,
DateTime absoluteExpiration,
TimeSpan slidingExpiration,
CacheItemPriority priority,
CacheItemRemovedCallback^ onRemoveCallback
)
member Add :
key:string *
value:Object *
dependencies:CacheDependency *
absoluteExpiration:DateTime *
slidingExpiration:TimeSpan *
priority:CacheItemPriority *
onRemoveCallback:CacheItemRemovedCallback -> Object
Parameters- key
- Type: System..::.String
The cache key used to reference the item.
- value
- Type: System..::.Object
The item to be added to the cache.
- dependencies
- Type: System.Web.Caching..::.CacheDependency
The file or cache key dependencies for the item. When any dependency changes, the object becomes invalid and is removed from the cache. If there are no dependencies, this parameter contains nullNothingnullptra null reference (Nothing in Visual Basic).
- absoluteExpiration
- Type: System..::.DateTime
The time at which the added object expires and is removed from the cache. If you are using sliding expiration, the absoluteExpiration parameter must be NoAbsoluteExpiration.
- slidingExpiration
- Type: System..::.TimeSpan
The interval between the time the added object was last accessed and the time at which that object expires. If this value is the equivalent of 20 minutes, the object expires and is removed from the cache 20 minutes after it is last accessed. If you are using absolute expiration, the slidingExpiration parameter must be NoSlidingExpiration.
- priority
- Type: System.Web.Caching..::.CacheItemPriority
The relative cost of the object, as expressed by the CacheItemPriority enumeration. The cache uses this value when it evicts objects; objects with a lower cost are removed from the cache before objects with a higher cost.
- onRemoveCallback
- Type: System.Web.Caching..::.CacheItemRemovedCallback
A delegate that, if provided, is called when an object is removed from the cache. You can use this to notify applications when their objects are deleted from the cache.
Return ValueType: System..::.ObjectAn object that represents the item that was added if the item was previously stored in the cache; otherwise, nullNothingnullptra null reference (Nothing in Visual Basic).

Exceptions
| Exception | Condition |
|---|
| ArgumentNullException | The key or value parameter is set to nullNothingnullptra null reference (Nothing in Visual Basic). | | ArgumentOutOfRangeException | The slidingExpiration parameter is set to less than TimeSpan.Zero or more than one year. | | ArgumentException | The absoluteExpiration and slidingExpiration parameters are both set for the item you are trying to add to the Cache. |

Remarks
Calls to this method will fail if an item with the same key parameter is already stored in the Cache. To overwrite an existing Cache item using the same key parameter, use the Insert method. You cannot set both the absoluteExpiration and slidingExpiration parameters. If you intend the cache item to expire at a specific time, you set the absoluteExpiration parameter to the specific time, and the slidingExpiration parameter to NoSlidingExpiration. If you intend the cache item to expire after a certain amount of time has passed since the item was last accessed, you set the slidingExpiration parameter to the expiration interval, and the absoluteExpiration parameter to NoAbsoluteExpiration.

Examples
The following example creates an AddItemToCache method. When this method is called, it sets an itemRemoved property to false and registers an onRemove method with a new instance of the CacheItemRemovedCallback delegate. The delegate's signature is used in the RemovedCallback method. The AddItemToCache method then checks the value associated with the Key1 key in the cache. If the value is nullNothingnullptra null reference (Nothing in Visual Basic), the Add method places an item in the cache with a key of Key1, a value of Value 1, an absolute expiration of 60 seconds, and a high cache priority. It also uses the onRemove method as an argument. This allows the RemovedCallback method to be called when this item is removed from the cache.
Public Sub AddItemToCache(sender As Object, e As EventArgs)
itemRemoved = false
onRemove = New CacheItemRemovedCallback(AddressOf Me.RemovedCallback)
If (IsNothing(Cache("Key1"))) Then
Cache.Add("Key1", "Value 1", Nothing, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove)
End If
End Sub
public void AddItemToCache(Object sender, EventArgs e) {
itemRemoved = false;
onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
if (Cache["Key1"] == null)
Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove);
}

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

See Also
|
Biblioteca de clases de .NET Framework Cache..::.Add (Método) Agrega el elemento especificado al objeto Cache con directivas de dependencias, expiración y prioridad, así como un delegado que se puede utilizar para notificar a la aplicación cuándo el elemento insertado se quita de la memoria Cache.
Espacio de nombres:
System.Web.Caching
Ensamblado:
System.Web (en System.Web.dll)

Sintaxis
Public Function Add ( _
key As String, _
value As Object, _
dependencies As CacheDependency, _
absoluteExpiration As DateTime, _
slidingExpiration As TimeSpan, _
priority As CacheItemPriority, _
onRemoveCallback As CacheItemRemovedCallback _
) As Object
public Object Add(
string key,
Object value,
CacheDependency dependencies,
DateTime absoluteExpiration,
TimeSpan slidingExpiration,
CacheItemPriority priority,
CacheItemRemovedCallback onRemoveCallback
)
public:
Object^ Add(
String^ key,
Object^ value,
CacheDependency^ dependencies,
DateTime absoluteExpiration,
TimeSpan slidingExpiration,
CacheItemPriority priority,
CacheItemRemovedCallback^ onRemoveCallback
)
member Add :
key:string *
value:Object *
dependencies:CacheDependency *
absoluteExpiration:DateTime *
slidingExpiration:TimeSpan *
priority:CacheItemPriority *
onRemoveCallback:CacheItemRemovedCallback -> Object
Parámetros- key
- Tipo: System..::.String
Clave de caché utilizada para hacer referencia al elemento.
- value
- Tipo: System..::.Object
Elemento que se va a agregar a la memoria caché.
- dependencies
- Tipo: System.Web.Caching..::.CacheDependency
Dependencias de archivo o de clave de caché para el elemento. Cuando cambia alguna dependencia, el objeto ya no es válido y se quita de la caché. Si no hay ninguna dependencia, este parámetro contiene nullNothingnullptrreferencia null (Nothing en Visual Basic).
- absoluteExpiration
- Tipo: System..::.DateTime
Hora a la que el objeto agregado expira y se quita de la memoria caché. Si se utiliza una expiración variable, el parámetro absoluteExpiration debe ser NoAbsoluteExpiration.
- slidingExpiration
- Tipo: System..::.TimeSpan
Intervalo entre la hora a la que se obtuvo por última vez acceso al objeto agregado y la hora a la que expira dicho objeto. Si este valor es el equivalente a 20 minutos, el objeto expirará y se quitará de la memoria caché a los 20 minutos del último acceso. Si se utiliza una expiración absoluta, el parámetro slidingExpiration debe ser NoSlidingExpiration.
- priority
- Tipo: System.Web.Caching..::.CacheItemPriority
Costo relativo del objeto, expresado por la enumeración de CacheItemPriority. La memoria caché utiliza este valor cuando extrae objetos; los objetos de costo inferior se quitan de la memoria caché antes que los objetos con un costo más elevado.
- onRemoveCallback
- Tipo: System.Web.Caching..::.CacheItemRemovedCallback
Delegado al que, si se proporciona, se llama cuando se quita un objeto de la memoria caché. Se puede utilizar para notificar a las aplicaciones cuándo se eliminan los objetos de la memoria caché.
Valor devueltoTipo: System..::.ObjectObjeto que representa el elemento que se agregó si el elemento estaba almacenado anteriormente en la memoria caché; de lo contrario, nullNothingnullptrreferencia null (Nothing en Visual Basic).

Excepciones
| Excepción | Condición |
|---|
| ArgumentNullException | El parámetro key o value se establece en nullNothingnullptrreferencia null (Nothing en Visual Basic). | | ArgumentOutOfRangeException | El parámetro slidingExpiration se establece en un valor menor que TimeSpan.Zero o en más de un año. | | ArgumentException | Los parámetros absoluteExpiration y slidingExpiration se establecen ambos para el elemento que se intenta agregar a Cache. |

Comentarios
Las llamadas a este método generarán un error si un elemento con el mismo parámetro key ya está almacenado en Cache. Para reemplazar un elemento Cache existente mediante el mismo parámetro key, utilice el método Insert. No puede establecer los parámetros absoluteExpiration y slidingExpiration al mismo tiempo. Si desea que el elemento de la caché expire a una hora determinada, establezca el parámetro absoluteExpiration en esa hora y el parámetro slidingExpiration en NoSlidingExpiration. Si desea que el elemento de la caché expire después de transcurrido un período de tiempo determinado a partir del momento en que se haya tenido acceso a él por última vez, establezca el parámetro slidingExpiration en el intervalo de expiración y el parámetro absoluteExpiration en NoAbsoluteExpiration.

Ejemplos
En el siguiente ejemplo se crea un método AddItemToCache. Cuando se llama a este método, establece una propiedad itemRemoved en false y registra un método onRemove con una nueva instancia del delegado CacheItemRemovedCallback. La firma del delegado se utiliza en el método RemovedCallback. A continuación, el método AddItemToCache comprueba el valor asociado a la clave Key1 de la caché. Si el valor es nullNothingnullptrreferencia null (Nothing en Visual Basic), el método Add coloca un elemento en la caché con una clave de Key1, un valor de Value 1, un período de expiración absoluta de 60 segundos y una prioridad de caché alta. También utiliza el método onRemove como argumento. Esto permite llamar el método RemovedCallback cuando se quita este elemento de la caché.
Public Sub AddItemToCache(sender As Object, e As EventArgs)
itemRemoved = false
onRemove = New CacheItemRemovedCallback(AddressOf Me.RemovedCallback)
If (IsNothing(Cache("Key1"))) Then
Cache.Add("Key1", "Value 1", Nothing, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove)
End If
End Sub
public void AddItemToCache(Object sender, EventArgs e) {
itemRemoved = false;
onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
if (Cache["Key1"] == null)
Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove);
}

Información de versión
.NET FrameworkCompatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0

Plataformas
Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2
.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Vea también
|