Remove Data from Cache with Named Tags
The items added with Named Tags to the cache can also be removed from the cache using the same named tag.
Similar to updating Named Tags; they can also be removed via CacheItem
. CacheItem is a custom class provided by NCache which can be used to add data to the cache.
In order to remove Named Tag via CacheItem the Named Tag property of the CacheItem is set as null
.
Pre-Requisites for Removing Named Tags
- Include the following namespace in your application:
Alachisoft.NCache.Web.Caching
Alachisoft.NCache.Runtime
- The application must be connected to cache before performing the operation.
- Cache must be running.
- Make sure that the data being added is serializable.
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
The following example removes the Named Tags via CacheItem
.
try
{
// Pre-condition: Cache is already connected
// CacheItem is already added in the cache with named tags iwth this key
string key = "1001";
// Retrieve the CacheItem using the key
CacheItem cacheItem = cache.GetCacheItem(key);
// Set the named tag property of the cacheItem as null
cacheItem.NamedTags = null;
// Re-insert the cacheItem in the cache with named tags removed
cache.Insert(key, cacheItem);
// CacheItem is successfully re-inserted in cache with removed named tags
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation performed during state transfer
// Operation Timeout
}
catch (Exception ex)
{
// Any other generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Note
cacheItem.NamedTags.Remove(tagName)
method will remove the Named Tag associated with the tag name tagName
. If all Named Tags are removed from the Named Tags dictionary and the cache item is then inserted into cache, Named Tags will be removed from that cache item since empty Named Tags dictionary indicates no Named Tags.
See also
Add/Update Items with Tags
Retrieving Items with Tag
SQL Query with NamedTags
SQL Delete with NamedTags