Async Operations
Asynchronous cache operations allow applications to perform cache reads and writes without blocking the calling thread. Instead of waiting for a cache operation to complete, the application can continue processing other work while NCache executes the request in the background.
Prerequisites
- Install the following NuGet packages in your .NET client application:
- Include the following namespaces in your application:
- The cache must be running.
- Make sure that the data being added is serializable.
- For API details, refer to: ICache, Add, Insert, CacheItem, CacheItemVersion, Count, Contains, AddAsync,InsertAsync, RemoveAsync, Version.
- Add the following Maven dependencies for your Java client application in
pom.xml file:
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<!--for NCache Enterprise-->
<artifactId>ncache-client</artifactId>
<version>x.x.x</version>
</dependency>
- Import the following packages in your Java client application:
- The cache must be running.
- Make sure that the data being added is serializable.
- For API details, refer to: Cache, add, insert, CacheItem, CacheItemVersion, getCount,addAsync, insertAsync, removeAsync, getVersion.
- Install either of the following NuGet packages in your .NET client application:
- Enterprise:
Install-Package Alachisoft.NCache.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.
Add Objects with Asynchronous API
AddAsync adds an item to the cache asynchronously and returns an object of the Task class which can be further used according to the business needs of the client application.
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);
// Adding item asynchronously. You can also add data by creating a CacheItem object which stores meta data as well
Task<CacheItemVersion> task = cache.AddAsync(customerKey, customer);
// This task object can be used as per your business needs
if (task.IsCompleted)
{
// Get CacheItemVersion object from task result
CacheItemVersion version = task.Result;
Console.WriteLine($"Item {customer.CustomerID} has been added to cache with version {version.Version}.");
}
// Precondition: Cache is already connected
String customerKey = "Customer:ALFKI";
Customer customer = fetchCustomerFromDB(customerKey);
cache.addAsync(customerKey, customer).get();
# Precondition: Cache is already connected
# Get product from database
product = fetch_product_from_db()
# Generate a unique cache key for this product string
key = f"Product:1001"
# Add Product object to cache asynchronously
async def add_async():
task = cache.add_async("key", "product")
value = await task
asyncio.run(add_async())
# This task object can be used as per your business needs
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);
CacheItem cacheItem = new CacheItem(customer);
// Adding item asynchronously. You can also add data by creating a CacheItem object which stores meta data as well
cache.AddAsync(customerKey, cacheItem, DSWriteOption.None, null);
Console.WriteLine($"Item {customer.CustomerID} has been added to cache.");
Update Objects with Asynchronous API
InsertAsync prevents thread-pool starvation by offloading cache operations to background threads, allowing the application to remain responsive during high-latency network events.
InsertAsync returns the object of the Task class which can further be used according to the business needs of the client application.
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
// Get customer from database if not found in cache
if (customer == null)
{
Customer customer = FetchCustomerFromDB("ALFKI");
}
// Update customer's Phone
customer.Phone = "12345-6789";
// Update customer in DB and Cache
if (UpdateDB(customer))
{
// Adding item asynchronously.
Task<CacheItemVersion> task = cache.InsertAsync(customerKey, customer);
// This task object can be used as per your business needs
if (task.IsCompleted)
{
// Get CacheItemVersion object from task result
CacheItemVersion version = task.Result;
Console.WriteLine($"Item {customer.CustomerID} has been updated with version {version.Version}.");
}
}
// Precondition: Cache is already connected
String customerKey = "Customer:ALFKI";
// Get customer from database if not found in cache
if (customer == null)
Customer customer = fetchCustomerFromDB("Customer:ALFKI");
// Update customer's Phone
customer.setPhone("12345-6789");
// Update cutsomer in DB and Cache
if (updateDB(customer)) {
// Adding item asynchronously.
FutureTask<CacheItemVersion> task = cache.insertAsync(customerKey, customer);
// Wait for task to complete and get CacheItemVersion object from task result
CacheItemVersion version = task.get();
System.out.println("Item " + customer.getCustomerID() + " has been updated with version " + version.getVersion() + ".");
}
# Precondition: Cache is already connected
# Get product from database
product = fetch_product_from_db()
# Generate a unique cache key for this product string
key = "Product:{product.get_product_id()}"
# Insert Product object to cache asynchronously
async def insert_async():
task = cache.insert_async("key", "product")
value = await task
asyncio.run(insert_async())
print("Item " + key + "has been updated.")
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);
CacheItem cacheItem = new CacheItem(customer);
if (customer == null)
{
// Adding item asynchronously.You can also add data by creating a CacheItem object which stores meta data as well
cache.InsertAsync(customerKey, cacheItem, DSWriteOption.None, null);
Console.WriteLine($"Item {customer.CustomerID} has been updated.")
}
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.");
See Also
.NET: Alachisoft.NCache.Client namespace.
Java: com.alachisoft.ncache.client namespace.
Python: ncache.client class.