Using Asynchronous Operations
To utilize the APIs, include the following namespace in your application:
Alachisoft.NCache.Web.Caching.
Adding Data to Cache Asynchronously
Data can be added to NCache asynchronously using AddAsync method.
Product product = new Product();
product.ProductID = 1001;
product.ProductName = "Chai";
CacheItem cacheItem = new CacheItem(product);
string key = "Product:" + product.ProductID;
try{
cache.AddAsync(key, cacheItem, DSWriteOption.None, null);
}
catch (Exception ex) {
// handle exception
}
Updating Data to Cache Asynchronously
The InsertAsync method enables you to update previously added data to the cache in an asynchronous manner.
Product product = new Product();
product.ProductID = 1001;
product.ProductName = "Chai";
product.Category = 5; // updated category
CacheItem cacheItem = new CacheItem(product);
string key = "Product:" + product.ProductID;
try{
cache.InsertAsync(key, cacheItem, DSWriteOption.None, null);
}
catch (Exception ex){
// handle exception
}
Removing Data from Cache Asynchronously
The RemoveAsync operation allows you to perform a remove operation in the background. In the following example you need to specify the key that has to be removed.
string key = "Product:1001";
try{
cache.RemoveAsync(key, null, DSWriteOption.None, null);
}
catch (Exception ex){
//handle exception
}
Clearing Cache Asynchronously
The ClearAsync method clears the cache completely in the background.
try
{
cache.ClearAsync(null);
}
catch (Exception ex)
{
// handle exception
}