Try Playground
Show / Hide Table of Contents

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

Prerequisites

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: ICache, Count, Remove, Contains, RemoveBulk, RemoveAsync.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: Cache, getCount, remove, removeBulk, removeAsync.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: Cache, CacheItem, get, get_cacheitem, get_bulk, remove, remove_bulk, remove_async.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: Cache, remove, removeBulk.
  • 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.

Remove Object From Cache

Note

This feature is also available in NCache Professional.

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.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected

// Unique cache key of product to remove
string key = $"Product:{product.ProductID}";

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
}
string key = "Product:1001";
Product product = null;
// null is returned if key does not exist in cache
object result = cache.Remove(key);
if (result != null)
{
    if (result is Product)
    {
        product = (Product)result;
    }
}
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.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
string customerKey = $"Customer:ALFKI";

cache.Remove(customerKey);
String customerKey = "ALFKI";

cache.delete(customerKey);
# Unique cache key of product to remove
key = "Product:1001"

# Remove specified item
cache.delete(key)
// Unique cache key of product to remove
var key = "Product:" + this.product.getProductID();

// Remove specified item
await this.cache.remove(key);
string key = "Product:1001";
cache.Delete(key);

Remove Bulk Items From Cache

Note

This feature is also available in NCache Professional.

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.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// 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);

    if (removedItems.Count != keysToRemove.Length)
        Console.WriteLine($"Failed to remove {keysToRemove.Length - removedItems.Count} items from cache.");
}
// 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);

    if (removedItems.size() != keysToRemove.size())
        System.out.println("Failed to remove " + (keysToRemove.size() - removedItems.size()) + " items from cache.");
}
# Get Products from database
products = fetch_products_from_db()

# Get keys to remove from cache
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 if any keys have failed to be removed
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")
// This is an async method
// Get Product from database against given ProductID
var products = await this.fetchProductFromDB();

// Get keys to fetch from cache
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 if any keys have failed to be retrieved

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
}
string[] keys = { "Product:1001", "Product:1002" };
IDictionary removedItems = cache.RemoveBulk(keys);

foreach (DictionaryEntry entry in removedItems)
{
    if (entry.Value is Product)
    {
        //do something
    }
}

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.

  • .NET
  • Java
  • Python
  • Legacy API
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.");
}
String customerKey = "Customer:ALFKI";
cache.removeAsync(customerKey, Customer.class);
System.out.println("Item '" + customerKey + "' has been removed.");
# Generate a unique cache key for this product
key = f"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())
# This task object can be used as per your business needs
string key = "Product:1001";
cache.RemoveAsync(key, null, DSWriteOption.None, null);

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.

In This Article
  • Prerequisites
  • Remove Object From Cache
  • Remove Bulk Items From Cache
  • Remove Objects From Cache With Asynchronous API
  • Additional Resources
  • See Also

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Professional
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top