• Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Try Playground
  • Client Side API Programming
  • Basic Operations - An Overview
  • Remove Data
Show / Hide Table of Contents
  • Programmer's Guide
  • Setting Up Development Environment
    • .NET
      • Client Development Environment
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Java
      • Client Development Environment
      • Client API Prerequisites
    • Python
      • Client Development Environment
      • Client API Prerequisites
    • Node.js
      • Client Development Environment
      • Client API Prerequisites
  • Client Side API Programming
    • Error Handling
    • Troubleshooting
    • Cache Keys and Data
    • How to Connect to Cache
    • Basic Operations - An Overview
      • Add Data
      • Update/Insert Data
      • Retrieve Data
      • Remove Data
    • Groups
      • Overview
      • Add/Update Data with Groups
      • Retrieve Data with Groups
      • Remove Data with Group
      • Search Group Data Using SQL
      • Delete Group Data Using SQL
    • Tags
      • Overview
      • Add/Update Data with Tags
      • Retrieve Data with Tags
      • Remove Data with Tags
      • Search Tag Data Using SQL
      • Delete Tag Data Using SQL
    • Named Tags
      • Overview
      • Add/Update Data with Named Tags
      • Remove Data with Named Tags
      • Search Data with Named Tags Using SQL
      • Delete Data with Named Tags Using SQL
    • Expirations
      • Overview
      • Absolute Expiration
      • Sliding Expiration
    • Data Dependency
      • Key Dependency
      • Multi-Cache Dependency
    • Dependency on Database
      • SQL Server
      • Oracle
      • OleDB with Polling
      • CLR Procedures in SQL Server
    • Dependency on External Source
      • File Dependency
      • Custom Dependency
      • Aggregate Dependency
    • Locks
      • Types of Locking
      • Pessimistic Locking
      • Optimistic Locking
    • SQL Query
      • Overview
      • Define Indexes Programmatically
      • Query with ExecuteReader and ExecuteScalar
      • Delete Data with ExecuteNonQuery
      • SQL Reference
    • LINQ Query
      • Overview
      • LINQ Query for Objects
      • LINQ Reference
    • Data Structures
      • Overview
      • List
      • Queue
      • Set
      • Dictionary
      • Counter
      • Invalidation Attributes
      • Searchable Attributes
      • Query on Data Structures
      • Remove from Data Structure
    • Events
      • Overview
      • Cache Level Events
      • Item Level Events
      • Management Level Events
    • Pub/Sub Messaging
      • Overview
      • Topics
      • Publish Messages
      • Subscribe to a Topic
      • Pub/Sub Events
      • Monitoring Topic Statistics
    • Continuous Query
      • Overview
      • Use Continuous Query
    • Stream Processing
      • Add/Update Stream Data
      • Retrieve Stream Data
    • JSON
      • Overview
      • Use JSON Objects
      • Query JSON Data
    • Security API
      • Login with Credentials
    • Management API
    • Error Logging
    • Location Affinity
  • Server-side API Programming
    • Loader and Refresher
      • Overview
      • Implement Loader and Refresher
      • Components of Loader/Refresher
    • Data Source Providers
      • Read-through
        • Implement Read-through
        • Use Read-through
      • Write-through
        • Implement Write-through
        • Use Write-through
        • Use Write-behind
        • Monitor Write-through Counters
    • Custom Dependency
      • Implement Extensible Dependency
      • Implement Bulk Extensible Dependency
      • Implement Notify Extensible Dependency
    • Bridge Conflict Resolver
    • Entry Processor
      • Overview
      • Implement Entry Processor
    • MapReduce
      • Overview
      • Implement MapReduce
      • Use MapReduce
    • MapReduce Aggregator
      • Overview
      • Implement and Use Aggregator
    • Compact Serialization
  • Client Side Features
    • ASP.NET Core Caching
      • Session Storage
        • Session Provider
        • IDistributedCache
        • Sessions Usage
        • Multi-site Session Provider
        • Session Sharing with ASP.NET
      • SignalR
        • NCache Extension for SignalR Core
      • Response Caching
        • Configure and Use
        • Configure with IDistributedCache
      • Data Caching
        • NCache API
        • IDistributedCache API
      • Data Protection Provider
        • Configure
    • Java Web App Caching
      • Web Sessions
        • Overview
        • Configure App
          • Add Maven Dependencies
          • Deploy Application
        • Multi-site Sessions
    • Node.js App Caching
      • Web Sessions
    • ASP.NET Caching Benefits and Overview
      • ASP.NET Session State Provider Properties
      • Multi-region ASP.NET Session State Provider Configuration
      • Session Sharing between ASP.NET and ASP.NET Core
      • ASP.NET SignalR Backplane
        • NCache Extension for SignalR
      • ASP.NET View State Caching
        • View State Content Optimization Configuration
        • Group View State with Sessions
        • Limit View State Caching
        • Page Level Grouping
      • ASP.NET Output Cache
        • Output Caching Provider Overview
        • Output Cache with Custom Hooks
  • .NET Third Party Integrations
    • Entity Framework (EF) Core
      • Installation
      • Configure
      • EF Core Extension Methods
        • Extension Methods
        • Cache Handle
        • Caching Options
        • Query Deferred API
      • Logging in EF Core
    • Entity Framework EF 6
      • EF Second Level Cache
      • EF Caching Resync Provider
      • EF Caching Configuration File
    • NHibernate
      • Second Level Cache
      • Query Caching
      • Synchronize Database with Cache
    • Debug NCache Providers in Visual Studio
  • Java Third Party Integrations
    • Hibernate
      • Second Level Cache
      • Configure Cacheable Objects and Regions
      • Configure Application
      • Query Caching
    • Spring
      • Overview
      • Use NCache with Spring
        • Configure Generic Provider
        • Configure JCache Spring Caching Provider
        • Configure Caching Declaration
        • Configure Spring Sessions
    • JCache API
      • CRUD Operations
      • Expiration
      • Events
  • Third-Party Wrappers
    • AppFabric to NCache Migration
      • AppFabric API vs. NCache API
      • Configuration Differences Between AppFabric and NCache
      • Migrating from an AppFabric Application to NCache
    • Redis to NCache Migration
      • Redis to NCache Migration
    • Memcached Wrapper
      • Memcached Gateway Approach
      • Memcached Client Plugin for .NET

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