Cache.Add(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback) Метод
Определение
Добавление указанного элемента в объект Cache с зависимостями, политиками сроков действия и приоритетов, а также с делегатом, которого можно использовать для уведомления приложения при удалении вставленного элемента из Cache
.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
.
public:
System::Object ^ Add(System::String ^ key, System::Object ^ value, System::Web::Caching::CacheDependency ^ dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, System::Web::Caching::CacheItemPriority priority, System::Web::Caching::CacheItemRemovedCallback ^ onRemoveCallback);
public object Add (string key, object value, System.Web.Caching.CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, System.Web.Caching.CacheItemPriority priority, System.Web.Caching.CacheItemRemovedCallback onRemoveCallback);
member this.Add : string * obj * System.Web.Caching.CacheDependency * DateTime * TimeSpan * System.Web.Caching.CacheItemPriority * System.Web.Caching.CacheItemRemovedCallback -> obj
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
Параметры
- key
- String
Ключ кэша, используемый для ссылки на элемент.The cache key used to reference the item.
- value
- Object
Элемент, добавляемый в кэш.The item to be added to the cache.
- dependencies
- CacheDependency
Зависимости файла или ключа кэша для элемента.The file or cache key dependencies for the item. Если какая-либо зависимость меняется, объект становится недопустимым и удаляется из кэша.When any dependency changes, the object becomes invalid and is removed from the cache. Если зависимости отсутствуют, данный параметр имеет значение null
.If there are no dependencies, this parameter contains null
.
- absoluteExpiration
- DateTime
Время истечения срока действия добавленного объекта и его удаления из кэша.The time at which the added object expires and is removed from the cache. Если используется скользящий срок действия, параметр absoluteExpiration
должен быть NoAbsoluteExpiration.If you are using sliding expiration, the absoluteExpiration
parameter must be NoAbsoluteExpiration.
- slidingExpiration
- TimeSpan
Интервал между временем последнего обращения к добавленному объекту и временем истечения срока действия этого объекта.The interval between the time the added object was last accessed and the time at which that object expires. Если это значение равно 20 минутам, срок действия объекта истечет, и он будет удален из кэша через 20 минут после последнего обращения к этому объекту.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. Если используется абсолютный срок действия, параметр slidingExpiration
должен быть NoSlidingExpiration.If you are using absolute expiration, the slidingExpiration
parameter must be NoSlidingExpiration.
- priority
- CacheItemPriority
Относительная цена объекта, выраженная перечислением 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
- 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.
Возвращаемое значение
Объект, представляющий добавленный элемент, если элемент был сохранен в кэше ранее; в противном случае — значение null
.An object that represents the item that was added if the item was previously stored in the cache; otherwise, null
.
Исключения
Для параметра key
или value
указано значение null
.The key
or value
parameter is set to null
.
Для параметра slidingExpiration
указано значение меньше TimeSpan.Zero
или больше одного года.The slidingExpiration
parameter is set to less than TimeSpan.Zero
or more than one year.
Оба параметра — absoluteExpiration
и slidingExpiration
— заданы для элемента, который вы пытаетесь добавить в Cache
.The absoluteExpiration
and slidingExpiration
parameters are both set for the item you are trying to add to the Cache
.
Примеры
В следующем примере создается AddItemToCache
метод.The following example creates an AddItemToCache
method. При вызове этого метода он устанавливает itemRemoved
свойство в значение false
и регистрирует onRemove
метод с новым экземпляром CacheItemRemovedCallback делегата.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. Сигнатура делегата используется в RemovedCallback
методе.The delegate's signature is used in the RemovedCallback
method. AddItemToCache
Затем метод проверяет значение, связанное с Key1
ключом в кэше.The AddItemToCache
method then checks the value associated with the Key1
key in the cache. Если значение равно null
, Add
метод помещает элемент в кэш с ключом Key1
, значением Value 1
, абсолютным сроком действия 60 секунд и высоким приоритетом кэша.If the value is null
, 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. В нем также используется onRemove
метод в качестве аргумента.It also uses the onRemove
method as an argument. Это позволяет RemovedCallback
вызывать метод при удалении этого элемента из кэша.This allows the RemovedCallback
method to be called when this item is removed from the cache.
Примечание
Примеры использования CacheDependency класса и CacheItemRemovedCallback делегата см. в разделе кэширование данных приложения.For examples of how to use the CacheDependency class and the CacheItemRemovedCallback delegate, see Caching Application Data.
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);
}
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
Комментарии
Вызовы этого метода будут завершаться сбоем автоматически, если элемент с таким же key
параметром уже сохранен в Cache
.Calls to this method will fail silently if an item with the same key
parameter is already stored in the Cache
. Чтобы перезаписать существующий Cache
элемент с помощью того же key
параметра, используйте Insert метод.To overwrite an existing Cache
item using the same key
parameter, use the Insert method.
Нельзя задать оба absoluteExpiration
slidingExpiration
параметра и.You cannot set both the absoluteExpiration
and slidingExpiration
parameters. Если вы планируете истечение срока действия элемента кэша в определенное время, задайте absoluteExpiration
параметру определенное время, а параметр — значение slidingExpiration
NoSlidingExpiration .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.
Если вы собираетесь истечь срок действия элемента кэша по истечении определенного промежутка времени с момента последнего обращения к элементу, задайте slidingExpiration
для параметра значение интервал, а absoluteExpiration
для параметра — значение NoAbsoluteExpiration .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.