Remove Cache Data
NCache provides the following two overloads with different return types to remove the object(s) from the cache data by accepting the cache item key(s) as the input parameter.
bool Remove<T>
void Remove
Note
This feature is also available in the NCache Community Edition, except for asynchronous operations.
Prerequisites
- Install either of the following NuGet packages in your .NET client application:
- Enterprise:
Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
- Professional:
Install-Package Alachisoft.NCache.Professional.SDK -Version 4.9.1.0
- Create a new Console Application.
- Make sure that the data being added is serializable.
- Add NCache References by locating
%NCHOME%\NCache\bin\assembly\4.0
and adding Alachisoft.NCache.Web
and Alachisoft.NCache.Runtime
as appropriate.
- Include the
Alachisoft.NCache.Web.Caching
namespace in your application.
- To learn more about the NCache Legacy API, please download the NCache 4.9 documents available as a .zip file on the Alachisoft Website.
Remove Object From Cache
An object of a custom class can be removed from the cache data using any of the Remove
methods.
Important
If an item does not exist in the cache data, null is returned.
Tip
One quick way to verify whether an item has been removed is to use either of the following properties of the cache class:
Count
returns the number of items present in the cache.
Contains
verifies if a specified key exists in the cache.
The following example removes the item corresponding to the specified key and casts the returned object into a Customer object to check whether the object is of Customer type or not. If not, it is added back to the cache.
// Precondition: Cache is already connected
// Unique cache key of product to remove
string customerKey = $"Customer:ALFKI";
// Create an object to store removed item
Customer customerRemoved = null;
// Remove specified item from cache
bool isItemRemoved = cache.Remove(customerKey, out customerRemoved);
if (isItemRemoved)
{
Console.WriteLine($"Customer with ID {customerRemoved.CustomerID} has been removed");
}
// Precondition: Cache is already connected
String customerKey = "ALFKI";
// Remove the cache item from the cache
cache.remove(customerKey, Customer.class);
System.out.println("Cache item with key " + customerKey + " has been removed.");
# Precondition: Cache is already connected
# Unique cache key of product to remove
key = "Product:1001"
# Remove specified item
item_removed = cache.remove(key, Product)
# Check if object is returned
if item_removed is not None:
# Perform operations
print(item_removed)
else:
# Item does not exist in cache
print("Key not found.")
// Precondition: Cache is already connected
// This is an async method
// Unique cache key of product to remove
var key = "Product:" + this.product.getProductID();
// To return item removed
var itemRemoved = new Product();
// Remove specified item
await this.cache.remove(key,itemRemoved);
// Check if object is returned
if (itemRemoved != null)
{
// Check if it is of Product type
if (itemRemoved instanceof Product)
{
// Perform operations
}
else
{
// The object removed was not of Product type
// Add it back to the cache
var ver = await this.cache.add(key, itemRemoved);
}
}
else
{
// Item does not exist in cache
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
// Create an object to store removed item
Customer customerRemoved = null;
// Remove specified item from cache
object isItemRemoved = cache.Remove(customerKey);
if (isItemRemoved != null && isItemRemoved is Customer)
{
customerRemoved = (Customer)isItemRemoved;
Console.WriteLine($"Customer with ID {customerRemoved.CustomerID} has been removed");
}
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
If you want to save your computational cost, you can use the void Remove
function that does not return anything and thus performs faster. Here is how you can use it.
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
// Delete specified item
cache.Remove(customerKey);
// Precondition: Cache is already connected
String customerKey = "ALFKI";
// Delete specified item
cache.delete(customerKey);
# Precondition: Cache is already connected
key = "Product:1001"
# Delete specified item
cache.delete(key)
// Precondition: Cache is already connected
var key = "Product:" + this.product.getProductID();
// Delete specified item
await this.cache.remove(key);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
// Delete specified item
cache.Delete(customerKey);
Remove Bulk Items From Cache
NCache provides a RemoveBulk
method to remove a bulk of cache items against the specified array of cache keys. It returns a dictionary of the keys and objects removed from the cache.
Important
If the specified items exist in the cache, a dictionary of the keys and objects removed is returned.
Tip
One quick way to verify whether an item has been removed is to use either of the following properties of the cache class:
Count
returns the number of items present in the cache.
Contains
verifies if a specified key exists in the cache.
The following example removes a bulk of existing cache items and casts the returned object into Customer objects.
// Precondition: Cache is already connected
// Create an array of all keys to remove
String[] keysToRemove = new String[]
{
"Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT", "Customer:BERGS"
};
// Create dictionary to store removed items
IDictionary<string, Customer> removedItems;
// Remove items from DB
if (DeleteFromDB(keysToRemove))
{
// Remove bulk items from cache
cache.RemoveBulk(keysToRemove, out removedItems);
// Check for failed removals
if (removedItems.Count != keysToRemove.Length)
{
Console.WriteLine($"Failed to remove {keysToRemove.Length - removedItems.Count} items from cache.");
}
}
// Precondition: Cache is already connected
// Create an array of all keys to remove
var keysToRemove = List.of("Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT", "Customer:BERGS");
// Create dictionary to store removed items
Map<String, Customer> removedItems;
// Remove items from DB
if (deleteFromDB(keysToRemove)) {
// Remove bulk items from cache
removedItems = cache.removeBulk(keysToRemove, Customer.class);
// Check for failed removals
if (removedItems.size() != keysToRemove.size())
System.out.println("Failed to remove " + (keysToRemove.size() - removedItems.size()) + " items from cache.");
}
# Precondition: Cache is already connected
# Create an array of all keys to remove
products = fetch_products_from_db()
keys = []
index = 0
for product in products:
keys[index] = "Product:" + product.get_product_id()
index = index + 1
# Remove bulk from cache
removed_items = cache.remove_bulk(keys, Product)
# Check for failed removals
if len(removed_items) is len(keys):
# Perform operations according to business logic
print("All the items were removed successfully")
else:
# Not all the keys are present in cache
print("Some of the keys were not removed")
// Precondition: Cache is already connected
// This is an async method
// Create an array of all keys to remove
var products = await this.fetchProductFromDB();
var keys = [products.length];
var index = 0;
products.forEach(product => {
keys[index] ="Product:" + this.product.getProductID();
index++;
});
// Get bulk from cache
var removedItems = await this.cache.removeBulk(keys);
// Check for failed removals
if(removedItems.size() > 0)
{
removedItems.forEach(entry => {
if(entry.getValue() instanceof Product)
{
var prod = entry.getValue();
// Perform operations according to business logic
}
else
{
// Object not of Product type
}
});
}
else
{
// No objects removed
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Create an array of all keys to remove
String[] keysToRemove = new String[]
{
"Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT", "Customer:BERGS"
};
// Remove items from cache
IDictionary removedItems = cache.RemoveBulk(keysToRemove);
// Check for failed removals
if (removedItems.Count < keysToRemove.Length)
{
var missingKeys = new HashSet<string>(keysToRemove);
foreach (DictionaryEntry entry in removedItems)
{
missingKeys.Remove((string)entry.Key);
Console.WriteLine($"Failed to remove {keysToRemove.Length - removedItems.Count} items from cache.");
}
}
Remove Objects From Cache With Asynchronous API
RemoveAsync
returns object of the Task class that can be further used according to the business needs of the client application. NCache provides three different status flags to notify the success or failure of the operation.
Important
Unlike Remove
and RemoveBulk
, RemoveAsync
does not generally return the removed objects to the application as it is an asynchronous operation and has to be fetched.
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
// Remove specified item from cache
Task<Customer> task = cache.RemoveAsync<Customer>(customerKey);
// This task object can be used as per your business needs
if (task.IsCompleted)
{
// Get Customer object from task result
Customer customer = task.Result;
Console.WriteLine($"Item {customer.CustomerID} has been removed.");
}
// Precondition: Cache is already connected
String customerKey = "Customer:ALFKI";
cache.removeAsync(customerKey, Customer.class);
System.out.println("Item '" + customerKey + "' has been removed.");
# Precondition: Cache is already connected
# Generate a unique cache key for this product
key = "Product:1001"
# Remove Product object from cache asynchronously
async def remove_async():
task = cache.remove_async(key, Product)
value = await task
asyncio.run(remove_async())
print("Item " + key + "has been removed.")
# This task object can be used as per your business needs
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
string key = $"Customer:ALFKI";
// Remove specified item from cache
cache.RemoveAsync(key, null, DSWriteOption.None, null);
Console.WriteLine($"Item {customer.CustomerID} has been removed.");
Additional Resources
NCache provides the sample application for Basic Operations on GitHub.
See Also
.NET: Alachisoft.NCache.Client namespace.
Java: com.alachisoft.ncache.client namespace.
Python: ncache.client class.
Node.js: Cache class.