Cache.Insert Метод
Определение
Перегрузки
Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback) |
Вставка объекта в объект Cache с зависимостями, политиками сроков действия и приоритетов, а также с делегатом, которого можно использовать для уведомления приложения при удалении вставленного элемента из |
Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemUpdateCallback) |
Вставляет в объект Cache объект с зависимостями, политиками сроков действия и делегатом, который можно использовать для уведомления приложения перед удалением элемента из кэша.Inserts an object into the Cache object together with dependencies, expiration policies, and a delegate that you can use to notify the application before the item is removed from the cache. |
Insert(String, Object, CacheDependency) |
Вставка объекта в Cache, имеющий зависимости файла или ключа.Inserts an object into the Cache that has file or key dependencies. |
Insert(String, Object) |
Вставка элемента в объект Cache с ключом кэша для ссылки на его расположение с помощью значений по умолчанию, предоставленных перечислением CacheItemPriority.Inserts an item into the Cache object with a cache key to reference its location, using default values provided by the CacheItemPriority enumeration. |
Insert(String, Object, CacheDependency, DateTime, TimeSpan) |
Вставка объекта в Cache с зависимостями и политиками сроков действия.Inserts an object into the Cache with dependencies and expiration policies. |
Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback)
Вставка объекта в объект Cache с зависимостями, политиками сроков действия и приоритетов, а также с делегатом, которого можно использовать для уведомления приложения при удалении вставленного элемента из Cache
.Inserts an object into 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:
void Insert(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 void Insert (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.Insert : string * obj * System.Web.Caching.CacheDependency * DateTime * TimeSpan * System.Web.Caching.CacheItemPriority * System.Web.Caching.CacheItemRemovedCallback -> unit
Public Sub Insert (key As String, value As Object, dependencies As CacheDependency, absoluteExpiration As DateTime, slidingExpiration As TimeSpan, priority As CacheItemPriority, onRemoveCallback As CacheItemRemovedCallback)
Параметры
- key
- String
Ключ кэша, используемый для ссылки на объект.The cache key used to reference the object.
- value
- Object
Объект для вставки в кэш.The object to be inserted in 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 inserted object expires and is removed from the cache. Чтобы избежать возможных проблем с местным временем, например перехода от стандартного времени к летнему, используйте для этого параметра значение UtcNow, а не Now.To avoid possible issues with local time such as changes from standard time to daylight saving time, use UtcNow rather than Now for this parameter value. Если используется абсолютный срок действия, параметр slidingExpiration
должен быть NoSlidingExpiration.If you are using absolute expiration, the slidingExpiration
parameter must be NoSlidingExpiration.
- slidingExpiration
- TimeSpan
Интервал между временем последнего обращения к вставленному объекту и временем истечения срока действия этого объекта.The interval between the time the inserted 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 will expire and be removed from the cache 20 minutes after it was last accessed. Если используется скользящий срок действия, параметр absoluteExpiration
должен быть NoAbsoluteExpiration.If you are using sliding expiration, the absoluteExpiration
parameter must be NoAbsoluteExpiration.
- priority
- CacheItemPriority
Цена объекта относительно других элементов, сохраненных в кэше, выраженная перечислением CacheItemPriority.The cost of the object relative to other items stored in the cache, as expressed by the CacheItemPriority enumeration. Это значение используется в кэше при исключении объектов. Объекты с более низкой ценой удаляются из кэша раньше, чем объекты с более высокой ценой.This value is used by the cache 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, will be called when an object is removed from the cache. Его можно использовать для уведомления приложений при удалении объектов из кэша.You can use this to notify applications when their objects are deleted from the cache.
Исключения
Значение параметра key
или параметра value
— null
.The key
or value
parameter is null
.
Для параметра slidingExpiration
указывается значение меньше TimeSpan.Zero
или больше одного года.You set the slidingExpiration
parameter to less than TimeSpan.Zero
or the equivalent of 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
.
Примеры
В следующем примере показано, как назначить элементу высокий приоритет при вставке в Cache
объект приложения.The following example demonstrates how to assign an item high priority when you insert it into your application's Cache
object.
Примечание
Дополнительные сведения об использовании этого метода с CacheItemRemovedCallback делегатом см. в разделе инструкции. Уведомление приложения об удалении элемента из кэша.For more information about how to use this method with the CacheItemRemovedCallback delegate, see How to: Notify an Application When an Item Is Removed from the Cache.
Cache.Insert("DSN", connectionString, null, DateTime.Now.AddMinutes(2), TimeSpan.Zero, CacheItemPriority.High, onRemove);
Cache.Insert("DSN", connectionString, Nothing, DateTime.Now.AddMinutes(2), TimeSpan.Zero, CacheItemPriority.High, onRemove)
Комментарии
Этот метод будет перезаписывать существующий Cache
элемент с тем же key
параметром.This method will overwrite an existing Cache
item with the same key
parameter.
Нельзя задать оба 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 last access to the item, you set the slidingExpiration
parameter to the expiration interval, and the absoluteExpiration
parameter to NoAbsoluteExpiration.
См. также раздел
- DateTime
- TimeSpan
- CacheItemPriority
- CacheItemRemovedCallback
- Кэширование данных приложенияCaching Application Data
Применяется к
Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemUpdateCallback)
Вставляет в объект Cache объект с зависимостями, политиками сроков действия и делегатом, который можно использовать для уведомления приложения перед удалением элемента из кэша.Inserts an object into the Cache object together with dependencies, expiration policies, and a delegate that you can use to notify the application before the item is removed from the cache.
public:
void Insert(System::String ^ key, System::Object ^ value, System::Web::Caching::CacheDependency ^ dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, System::Web::Caching::CacheItemUpdateCallback ^ onUpdateCallback);
public void Insert (string key, object value, System.Web.Caching.CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, System.Web.Caching.CacheItemUpdateCallback onUpdateCallback);
member this.Insert : string * obj * System.Web.Caching.CacheDependency * DateTime * TimeSpan * System.Web.Caching.CacheItemUpdateCallback -> unit
Public Sub Insert (key As String, value As Object, dependencies As CacheDependency, absoluteExpiration As DateTime, slidingExpiration As TimeSpan, onUpdateCallback As CacheItemUpdateCallback)
Параметры
- key
- String
Ключ кэша, используемый для ссылки на объект.The cache key that is used to reference the object.
- value
- Object
Объект, вставляемый в кэш.The object to insert into 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 inserted object expires and is removed from the cache. Чтобы избежать возможных проблем с местным временем, например перехода от стандартного времени к летнему, используйте для этого параметра значение UtcNow вместо Now.To avoid possible issues with local time such as changes from standard time to daylight saving time, use UtcNow instead of Now for this parameter value. Если используется абсолютный срок действия, параметру slidingExpiration
следует присвоить значение NoSlidingExpiration.If you are using absolute expiration, the slidingExpiration
parameter must be set to NoSlidingExpiration.
- slidingExpiration
- TimeSpan
Интервал между временем последнего обращения к кэшируемому объекту и временем истечения срока действия этого объекта.The interval between the time that the cached 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 will expire and be removed from the cache 20 minutes after it was last accessed. Если используется скользящий срок действия, параметру absoluteExpiration
следует присвоить значение NoAbsoluteExpiration.If you are using sliding expiration, the absoluteExpiration
parameter must be set to NoAbsoluteExpiration.
- onUpdateCallback
- CacheItemUpdateCallback
Делегат, который будет вызываться перед удалением объекта из кэша.A delegate that will be called before the object is removed from the cache. Можно использовать этот вызов для обновления кэшируемого элемента, с тем чтобы он не был удален из кэша.You can use this to update the cached item and ensure that it is not removed from the cache.
Исключения
Параметр key
, value
или onUpdateCallback
имеет значение null
.The key
, value
, or onUpdateCallback
parameter is null
.
Для параметра slidingExpiration
указывается значение меньше TimeSpan.Zero
или больше одного года.You set the slidingExpiration
parameter to less than TimeSpan.Zero
or the equivalent of 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
.
-или--or-
Параметр dependencies
имеет значение null
, параметру absoluteExpiration
присвоено значение NoAbsoluteExpiration, а параметру slidingExpiration
— NoSlidingExpiration.The dependencies
parameter is null
, and the absoluteExpiration
parameter is set to NoAbsoluteExpiration, and the slidingExpiration
parameter is set to NoSlidingExpiration.
Комментарии
InsertМетод позволяет вставить новый элемент в кэш и предоставить делегат, вызываемый перед удалением элемента из кэша.The Insert method enables you to insert a new item in the cache and provide a delegate that is called before the item is removed from the cache. В делегате можно обновить кэшированный элемент и, таким образом, предотвратить его удаление из кэша.In the delegate, you can update the cached item and thereby prevent it from being removed from the cache.
Этот метод будет перезаписывать существующий Cache
элемент с тем же key
параметром.This method will overwrite an existing Cache
item with the same key
parameter.
Нельзя задать оба 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 set period of time since the item was last accessed, you set the slidingExpiration
parameter to the expiration interval, and you set the absoluteExpiration
parameter to NoAbsoluteExpiration.
См. также раздел
Применяется к
Insert(String, Object, CacheDependency)
public:
void Insert(System::String ^ key, System::Object ^ value, System::Web::Caching::CacheDependency ^ dependencies);
public void Insert (string key, object value, System.Web.Caching.CacheDependency dependencies);
member this.Insert : string * obj * System.Web.Caching.CacheDependency -> unit
Public Sub Insert (key As String, value As Object, dependencies As CacheDependency)
Параметры
- key
- String
Ключ кэша, используемый для определения элемента.The cache key used to identify the item.
- value
- Object
Объект для вставки в кэш.The object to be inserted in the cache.
- dependencies
- CacheDependency
Зависимости файла или ключа кэша для вставленного объекта.The file or cache key dependencies for the inserted object. Если какая-либо зависимость меняется, объект становится недопустимым и удаляется из кэша.When any dependency changes, the object becomes invalid and is removed from the cache. Если зависимости отсутствуют, данный параметр имеет значение null
.If there are no dependencies, this parameter contains null
.
Исключения
Значение параметра key
или параметра value
— null
.The key
or value
parameter is null
.
Примеры
В следующем примере показано, как вставить элемент в кэш приложения с зависимостью кэша от XML-файла конфигурации.The following example demonstrates how to insert an item into an application's cache with a cache dependency on an XML configuration file.
Cache.Insert("DSN", connectionString, new CacheDependency(Server.MapPath("myconfig.xml")));
Cache.Insert("DSN", connectionString, New CacheDependency(Server.MapPath("myconfig.xml")))
Комментарии
Этот метод будет перезаписывать существующий элемент кэша, ключ которого соответствует key
параметру.This method will overwrite an existing cache item whose key matches the key
parameter. Объект, добавляемый в кэш с помощью этой перегрузки Insert
метода, вставляется с приоритетом Default , значением скользящего срока действия NoSlidingExpiration и абсолютным значением срока действия NoAbsoluteExpiration .The object added to the cache using this overload of the Insert
method is inserted with a priority of Default, a sliding expiration value of NoSlidingExpiration, and an absolute expiration value of NoAbsoluteExpiration.
См. также раздел
Применяется к
Insert(String, Object)
Вставка элемента в объект Cache с ключом кэша для ссылки на его расположение с помощью значений по умолчанию, предоставленных перечислением CacheItemPriority.Inserts an item into the Cache object with a cache key to reference its location, using default values provided by the CacheItemPriority enumeration.
public:
void Insert(System::String ^ key, System::Object ^ value);
public void Insert (string key, object value);
member this.Insert : string * obj -> unit
Public Sub Insert (key As String, value As Object)
Параметры
- key
- String
Ключ кэша, используемый для ссылки на элемент.The cache key used to reference the item.
- value
- Object
Объект для вставки в кэш.The object to be inserted into the cache.
Исключения
Значение параметра key
или параметра value
— null
.The key
or value
parameter is null
.
Примеры
В следующем примере показано, как вставить элемент в кэш приложения.The following example demonstrates how to insert an item into an application's cache.
Cache.Insert("DSN", connectionString);
Cache.Insert("DSN", connectionString)
Комментарии
Этот метод будет перезаписывать существующий элемент кэша, ключ которого соответствует key
параметру.This method will overwrite an existing cache item whose key matches the key
parameter. Объект, добавленный в кэш с помощью этой перегрузки Insert
метода, вставляется без зависимостей файла или кэша, приоритет Default , значение скользящего срока действия NoSlidingExpiration и абсолютное значение срока действия NoAbsoluteExpiration .The object added to the cache using this overload of the Insert
method is inserted with no file or cache dependencies, a priority of Default, a sliding expiration value of NoSlidingExpiration, and an absolute expiration value of NoAbsoluteExpiration.
См. также раздел
Применяется к
Insert(String, Object, CacheDependency, DateTime, TimeSpan)
public:
void Insert(System::String ^ key, System::Object ^ value, System::Web::Caching::CacheDependency ^ dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration);
public void Insert (string key, object value, System.Web.Caching.CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration);
member this.Insert : string * obj * System.Web.Caching.CacheDependency * DateTime * TimeSpan -> unit
Public Sub Insert (key As String, value As Object, dependencies As CacheDependency, absoluteExpiration As DateTime, slidingExpiration As TimeSpan)
Параметры
- key
- String
Ключ кэша, используемый для ссылки на объект.The cache key used to reference the object.
- value
- Object
Объект для вставки в кэш.The object to be inserted in the cache.
- dependencies
- CacheDependency
Зависимости файла или ключа кэша для вставленного объекта.The file or cache key dependencies for the inserted object. Если какая-либо зависимость меняется, объект становится недопустимым и удаляется из кэша.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 inserted object expires and is removed from the cache. Чтобы избежать возможных проблем с местным временем, например перехода от стандартного времени к летнему, используйте для этого параметра значение UtcNow, а не Now.To avoid possible issues with local time such as changes from standard time to daylight saving time, use UtcNow rather than Now for this parameter value. Если используется абсолютный срок действия, параметр slidingExpiration
должен быть NoSlidingExpiration.If you are using absolute expiration, the slidingExpiration
parameter must be NoSlidingExpiration.
- slidingExpiration
- TimeSpan
Интервал между временем последнего обращения к вставленному объекту и временем истечения срока действия этого объекта.The interval between the time the inserted object is last accessed and the time at which that object expires. Если это значение равно 20 минутам, срок действия объекта истекает и он удаляется из кэша через 20 минут после последнего обращения.If this value is the equivalent of 20 minutes, the object will expire and be removed from the cache 20 minutes after it was last accessed. Если используется скользящий срок действия, параметр absoluteExpiration
должен быть NoAbsoluteExpiration.If you are using sliding expiration, the absoluteExpiration
parameter must be NoAbsoluteExpiration.
Исключения
Значение параметра key
или параметра value
— null
.The key
or value
parameter is null
.
Для параметра slidingExpiration
указывается значение меньше TimeSpan.Zero
или больше одного года.You set the slidingExpiration
parameter to less than TimeSpan.Zero
or the equivalent of 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
.
Примеры
В следующем примере показано, как вставить элемент в кэш приложения с абсолютным сроком действия.The following example demonstrates how to insert an item into an application's cache with an absolute expiration.
Примечание
Так как эта форма Insert
метода поддерживает зависимости кэша, если элемент не имеет зависимостей, необходимо объявить dependency
параметр как null
( Nothing
в Visual Basic) в списке параметров, разделенных запятыми.Since this form of the Insert
method supports cache dependencies, if the item has no dependencies, you must declare the dependency
parameter as null
(Nothing
in Visual Basic) in the comma-delimited list of parameters.
Cache.Insert("DSN", connectionString, null, DateTime.Now.AddMinutes(2), Cache.NoSlidingExpiration);
Cache.Insert("DSN", connectionString, Nothing, DateTime.Now.AddMinutes(2), Cache.NoSlidingExpiration)
В следующем примере показано, как вставить элемент в кэш с скользящей истечением срока действия.The following example demonstrates how to insert an item into the cache with a sliding expiration.
Cache.Insert("DSN", connectionString, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(10));
Cache.Insert("DSN", connectionString, Nothing, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(10))
Комментарии
Этот метод будет перезаписывать существующий Cache
элемент с тем же key
параметром.This method will overwrite an existing Cache
item with the same key
parameter.
Если slidingExpiration
параметр имеет значение NoSlidingExpiration , скользящий срок действия отключен.If the slidingExpiration
parameter is set to NoSlidingExpiration, sliding expiration is disabled. Если для параметра задано значение slidingExpiration
больше Zero , то absoluteExpiration
параметр задается равным Now плюс значению, содержащемуся в slidingExpiration
параметре.If you set the slidingExpiration
parameter to greater than Zero, the absoluteExpiration
parameter is set to Now plus the value contained in the slidingExpiration
parameter. Если элемент запрашивается из кэша до времени absoluteExpiration
, указанного параметром, элемент снова помещается в кэш и absoluteExpiration
снова задается в DateTime.Now
плюс значение, содержащееся в slidingExpiration
параметре.If the item is requested from the cache before the amount of time specified by the absoluteExpiration
parameter, the item will be placed in the cache again, and absoluteExpiration
will again be set to DateTime.Now
plus the value contained in the slidingExpiration
parameter. Если элемент не запрашивается из кэша до даты в absoluteExpiration
параметре, элемент удаляется из кэша.If the item is not requested from the cache before the date in the absoluteExpiration
parameter, the item is removed from the cache. Элемент, добавленный в кэш с помощью этой перегрузки метода Insert, вставляется с приоритетом Default .The item added to the cache using this overload of the insert method is inserted with a priority of Default.