Emptying the Cache
NCache allows clients to empty the cache in one call completely, without relying on data invalidation strategies like expiration and eviction. Emptying the cache results in the cache going into a "fresh" state, as all keys and associated items and metadata are removed from the cache. Caches can be cleared either synchronously or asynchronously.
In case of client cache configured, NCache provides separate methods to clear the client cache, irrespective of the remote cache.
Remote Cache
Synchronous
The following example initializes a remote cache myPartitionedCache, performs some operations and uses the Clear() method to empty the cache synchronously.
Cache cache = NCache.InitializeCache("myPartitionedCache");
// Add items, perform operations
cache.Clear();
Asynchronous
ClearAsync() allows you to clear the cache asynchronously, so the application does not wait for the operation to complete and carries on with further operations.
The following example empties the cache myPartitionedCache asynchronously. However, you can register a callback to get notified whether the operation has successfully completed or not.
try
{
// Clear Cache callback specified here
cache.ClearAsync(new AsyncCacheClearedCallback(OnCacheCleared));
}
catch (OperationFailedException ex)
{
// Handle exception
}
...
// Create a callback method
public static void OnCacheCleared(object status)
{
if (status is Exception)
{
// Handle exception
}
else if (status.ToString().Equals("Success"))
{
// Cache cleared
}
}
Client Cache
A client cache is a local cache synchronized with the remote clustered cache. All operations on the remote cache are synchronized with the client cache. However, you can independently clear the client cache, which will then synchronize itself with the current state of the remote cache.
- Synchronous
The following example initializes an existing client cache myClientCache, performs some operations and uses the ClearClientCache() method to empty the client cache synchronously.
Cache cache = NCache.InitializeCache("myClientCache");
// Add items, perform operations
cache.ClearClientCache();
- Asynchronous
The following example clears the client cache myClientCache asynchronously, using the ClearClientCacheAsync. However, you can register a callback to get notified whether the operation has successfully completed or not.
try
{
// Clear Cache callback specified here
cache.ClearClientCacheAsync(new AsyncCacheClearedCallback(OnCacheCleared));
}
catch (OperationFailedException ex)
{
// Handle exception
}
...
// Create a callback method
public static void OnCacheCleared(object status)
{
if (status is Exception)
{
// Handle exception
}
else if (status.ToString().Equals("Success"))
{
// Cache cleared
}
}
See Also
Add Data to Cache
Update Data to Cache
Retrieve Data from Cache
Remove Data from Cache