Remove Data from Cache
For large amount of data in cache, there can be some data which turns stale over time or is not needed for further operations by the application. For this, NCache allows removing items from the cache, which frees up space in the cache and ensures data consistency and freshness.
NCache provides two methods (Remove and Delete) to facilitate removal of objects from the cache. These methods take the cache item key(s) as their parameter. While both methods remove the specified items from the cache, they have difference in their return types which makes their uses unique and more flexible.
Remove() | Delete() |
---|---|
Returns the removed object to the application. | Returns nothing. |
When to Use Remove or Delete?
Remove Method
This is a fail safe option, as it allows checking whether the data removed should be really removed or not. In case the object removed is not the one you wanted to remove, the returned object can be added back to the cache.
For example, you want to remove a Product type object from the cache but the key provided is not explanatory to describe whether the object is Product type or not. Here, you can check whether the data removed is of Product data type. If it is not, it means the wrong object has been removed, and you can add it back to the cache.
Another use of Remove()
can be an e-commerce site which needs to remove the products which have less than 3 units available at the end of each business day. Hence, using Remove()
will remove the items from the cache, but return the objects back to the application so that a list of products running low on units can be maintained.
Delete Method
This approach is a faster operation compared to Remove()
, as it does not have the added operational cost of fetching the objects and returning them to the application. Delete()
can be used when you are sure of the data being removed.
For example, an e-commerce site removes those products which have been marked as "discontinued" in the data source but are still residing in the cache. In such a scenario, using Delete()
will be more efficient as the application does not require keeping track of the products which are no longer available.
Remove/Delete Operation Behavior
Data can be removed from NCache either as a single item, bulk of items or asynchronously.
Remove will return the removed object to the application. If the keys specified do not exist, null will be returned and no exception will be thrown.
Delete will return nothing to the application. If the keys specified do not exist, no exception will be thrown.
In advanced cases, if data source is configured, data removal will occur in cache as well as data source. For more details, you can refer to the chapter Data Source Providers.
Pre-requisites For Removing Data
- Include the following namespace in your application:
Alachisoft.NCache.Web.Caching
. - The application must be connected to cache before performing the operation.
- Cache must be running.
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Remove Item(s)
Single Item
A single item can be removed from the cache, which is also returned to the application through the Remove() method.
Important
If the item does not exist in cache, null is returned.
Tip
One quick way to verify whether item has been removed, is to use either properties of the Cache class:
The following example removes the item corresponding to the specified key and casts the returned object into a Product
object to check whether the object is of Product type. If not, it is added back to the cache.
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
try
{
// Pre-condition: Cache is already connected
// Unique cache key of product to remove
string key = $"Product:{product.ProductID}";
// Remove specified item
object itemRemoved = cache.Remove(key);
// Check if object is returned
if (itemRemoved != null)
{
// Check if it is of Product type
if (itemRemoved is Product)
{
// Save object for future use as Product object
Product product = itemRemoved as Product
}
else
{
// The object removed was not of Product type
// Add it back to the cache
CacheItemVersion ver = cache.Add(key, itemRemoved);
}
}
else
{
// Item does not exist in cache
}
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failure
// Operation performed during state transfer
// Operation Timeout
}
Bulk Items
NCache provides RemoveBulk() method to remove a bulk of cache items against the specified array of cache keys. This returns a dictionary of the keys and objects removed from the cache.
Important
- If the specified items exist in cache, a dictionary of the keys and objects removed is returned.
- If the specified items do not exist in cache, nothing is returned for those items.
Although a bulk operation is executed as a single operation, the failure of operations is treated individually. For example, if a bulk of 100 items is removed from the cache and 20 of those items do not exist in the cache, the remaining 80 items will be removed from the cache and return to the application.
Tip
One quick way to verify whether item has been removed, is to use either properties of the Cache class:
The following example removes a bulk of existing cache items, and casts the returned object into Product
objects.
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
try
{
// Pre-condition: Cache is already connected
// Get Keys
Product[] products = FetchProductsFromDB();
string[] keys = new string[products.Length];
for (int i = 0; i < 100; i++)
{
// Using the same unique cache key for this product
keys[i] = $"Product:{products[i].ProductID}";
}
// Remove items
IDictionary itemsRemoved = cache.RemoveBulk(keys);
// Check if any keys have failed to be removed
if (itemsRemoved.Count == keys.Length)
{
foreach (DictionaryEntry entry in itemsRemoved)
{
if (entry.Value is Product)
{
Product prodcut = entry.Value as Product;
// Save object for future use as Product object
}
else
{
// Object not of Product type
}
}
}
else
{
// Not all of the keys are present in cache
foreach (var key in keys)
{
if (itemsRemoved.Contains(key) == false)
{
// This key does not exist in cache
}
}
}
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failure
// Operation performed during state transfer
// Operation Timeout
}
Asynchronous API
Asynchronous operations are performed in the background, so the client does not have to wait for the response from the server to execute further operations. The control is returned to the application immediately after performing the operation. This increases overall responsiveness of the application.
Since asynchronous operations do not notify upon the failure or success of the operations themselves, NCache provides a callback mechanism which can be registered while making the operation call. These callbacks are triggered upon success or failure of the operation.
The RemoveAsync() method allows removing cached items asynchronously, where nothing is returned since it is an asynchronous operation. However, if callback is registered, it will return the status of the operation.
Important
- Unlike Remove and RemoveBulk, RemoveAsync does not return the removed objects to the application as it is an asynchronous operation.
- Only if callback is registered, the status of the operation is returned through the callback.
Note
Note that this API also allows specifying additional parameters for Data Source Providers and Groups, so the values for those parameters have been passed as None
and null
respectively, as they are not discussed here.
The following example removes an existing cache item with the specified key, while registering a callback. The AsyncItemRemovedCallback
function is used to register a callback to perform appropriate functions upon completion of the operation. If the callback is not specified, the data will be removed without callback, using the same API.
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
try
{
// Pre-condition: Cache is already connected
// Unique cache key of product to remove
string key = $"Product:{product.ProductID}";
// Specify Callback
// If NOT specified, data will be asynchronously removed WITHOUT callback
cache.RemoveAsync(key, new AsyncItemRemovedCallback(OnItemRemoved), DSWriteOption.None, null);
}
catch (OperationFailedException ex)
{
// NCache specific exception
// Exception can occur due to Connection Failure
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
...
//Create a callback method
public static void OnItemRemoved(string key, object status)
{
if (status is Exception ex)
{
// Operation performed during state transfer
}
else
{
AsyncOpResult result = (AsyncOpResult)status;
if (result == AsyncOpResult.Success)
{
// Object removed from cache successfully
}
}
}
Delete Item(s)
Single Item
NCache allows deleting a single item from the cache for the specified key, using the Delete() method. If the key does not exist, no exception is thrown and the control is returned to the application.
Tip
One quick way to verify whether item has been removed, is to use either properties of the Cache class:
The following example deletes the cache item corresponding to the key specified.
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
//Get key
string key = GetKeyToDelete();
try
{
// Pre-condition: Cache is already connected
// Get key
Product product = GetProductByID(1001);
string key = GetProductKey(product);
// Delete item
cache.Delete(key);
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failure
// Operation performed during state transfer
// Operation Timeout
}
catch (Exception ex)
{
// Any other generic exception like ArgumentException, ArgumentNullException, etc..
}
Bulk Items
NCache also supports deleting items in bulk to reduce network cost. As with RemoveBulk(), DeleteBulk() removes the specified items from the cache based on the specified keys.
Important
No object is returned once operation is completed.
Tip
One quick way to verify whether item has been removed, is to use either properties of the Cache class:
The following example checks the cache count before deleting a bulk, deletes a bulk of items with keys specified and then checks the cache count again. If this difference is equal to the number of keys specified, it implies all keys have been successfully deleted from cache.
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
// Get keys
string[] keys = GetKeysToDelete();
try
{
// Pre-condition: Cache is already connected
// Get Count of cache items before Delete
long countBeforeDelete = cache.Count;
// Delete specified items
cache.DeleteBulk(keys);
// Verify if keys have been deleted
// Get count of items after Delete
long countAfterDelete = cache.Count;
long keyCountDifference = countBeforeDelete - countAfterDelete;
if (keyCountDifference == keys.Count())
{
// All keys have been deleted
}
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Operation performed during state transfer
// Operation Timeout
}
See Also
Connecting to Cache
Add Data to Cache
Update Data to Cache
Retrieve Data from Cache
Start Cache