• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
Download
Show / Hide Table of Contents

Interface ICache

This interface contians the services and methods that are used to perform operations on the cache.

Assembly: Alachisoft.NCache.Client.dll
Syntax
public interface ICache : IDisposable, IEnumerable

Properties

ClientInfo

Displays the information related to this client.

Declaration
ClientInfo ClientInfo { get; }
Property Value
Type Description
ClientInfo

Displays the information related to this client.

ConnectedClientList

Gets the information of all connected clients to the cache.

Declaration
IList<ClientInfo> ConnectedClientList { get; }
Property Value
Type Description
System.Collections.Generic.IList<ClientInfo>

Provides the information of all connected clients to the cache.

Count

Gets the number of items stored in the cache.

Declaration
long Count { get; }
Property Value
Type Description
System.Int64

Number of items stored in the cache.

DataTypeManager

Gets an instance of IDataTypeManager.

Declaration
IDataTypeManager DataTypeManager { get; }
Property Value
Type Description
IDataTypeManager

It contains create and get operations for the ICounter and remove operation for all distributed data structures.

ExecutionService

Gets an instance of IExecutionService.

Declaration
IExecutionService ExecutionService { get; }
Property Value
Type Description
IExecutionService

It contains properties and methods required for the Execution Service.

MessagingService

Gets an instance of IMessagingService.

Declaration
IMessagingService MessagingService { get; }
Property Value
Type Description
IMessagingService

It contains the properties and methods required for the Messaging Service.

NotificationService

Gets an instance of INotificationService.

Declaration
INotificationService NotificationService { get; }
Property Value
Type Description
INotificationService

It contains properties and methods required for a Notification Service.

SearchService

Gets an instance of ISearchService.

Declaration
ISearchService SearchService { get; }
Property Value
Type Description
ISearchService

It contains properties and methods required for Search Service.

Methods

Add(String, CacheItem, WriteThruOptions)

Adds a CacheItem to the cache. It also lets you specify the WriteThruOptions. Using CacheItem, you can also specify properties for the cache items, for e.g., expiration and priority.

Declaration
CacheItemVersion Add(string key, CacheItem item, WriteThruOptions writeThruOptions = null)
Parameters
Type Name Description
System.String key

Unique key to identify the cache item.

CacheItem item

CacheItem that is to be stored in the cache.

WriteThruOptions writeThruOptions

WriteThruOptions regarding updating the data source. This can be either WriteThru, WriteBehind or none.

Returns
Type Description
CacheItemVersion

Represents the version of each cache item.

Remarks

If CacheItem contains invalid values, the related exception is thrown. See CacheItem for invalid property values and related exceptions.

Examples

The following example demonstrates how to add an item to the cache with a sliding expiration of 5 minutes and a high priority.

ICache cache = CacheManager.GetCache("demoClusteredCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

CacheItem item = new CacheItem(product);
item.Expiration = new Expiration(ExpirationType.Sliding,new TimeSpan(0, 5, 0));
item.Priority = CacheItemPriority.High;

string key = "Product0";

WriteThruOptions writeThruOptions = new WriteThruOptions(WriteMode.WriteThru, "ProdDataSource1");

cache.Add(key, item, writeThruOptions);

Add(String, Object)

Adds an item into the cache with a cache key to reference its location.

Declaration
CacheItemVersion Add(string key, object value)
Parameters
Type Name Description
System.String key

Unique key to identify the cache item.

System.Object value

The item (object) to be stored in the cache.

Returns
Type Description
CacheItemVersion

Represents the version of each cache item.

Examples

The following example demonstrates how to add a value to cache.

ICache cache = CacheManager.GetCache("demoClusteredCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

string key = "Product0";

cache.Add(key, product);

AddAsync(String, CacheItem, WriteThruOptions)

Adds a CacheItem into the cache asynchronously, with a cache key to reference its location and WriteThruOptions.

Declaration
Task<CacheItemVersion> AddAsync(string key, CacheItem item, WriteThruOptions writeThruOptions = null)
Parameters
Type Name Description
System.String key

Unique key to identify the cache item.

CacheItem item

CacheItem that is to be stored in the cache.

WriteThruOptions writeThruOptions

WriteThruOptions regarding updating the data source. This can be either WriteThru, WriteBehind or none.

Returns
Type Description
System.Threading.Tasks.Task<CacheItemVersion>

Task that performs an add operation in the background. Once completed returns version of cache item that was added in cache. Task Status property can be used to determine status of the Task that can be IsCanceled, IsCompleted, and IsFaulted.

Examples

The following example demonstrates how to add an CacheItem to the cache asynchronously, with registering a Task to monitor the status of the operation along with WriteThruOptions.

ICache cache = CacheManager.GetCache("demoClusteredCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

CacheItem item = new CacheItem(product);

string key = "Product0";

WriteThruOptions writeThruOptions = new WriteThruOptions(WriteMode.WriteThru, "ProdDataSource1");

cache.AddAsync(key, item, writeThruOptions).ContinueWith(task => OnItemAdded(key, task));

private static void OnItemAdded(string key, Task<CacheItemVersion> task)
{
    if (task.Status == TaskStatus.RanToCompletion)
    {
    ...
    }
    if (task.Status == TaskStatus.Faulted)
    {
    ...
    }
    if (task.Exception != null)
    {
    ...
    }
}

AddAsync(String, Object)

Adds an object into the cache asynchronously, with a cache key to reference its location.

Declaration
Task<CacheItemVersion> AddAsync(string key, object value)
Parameters
Type Name Description
System.String key

Unique key to identify the cache item.

System.Object value

The item (object) to be stored in the cache.

Returns
Type Description
System.Threading.Tasks.Task<CacheItemVersion>

Task that performs an add operation in the background. Once the Task is completed, it will return the version of cache item that was added in cache. Task contains the status of the operation taking place in the background. That status can be one out of them completed, canceled, running or faulted.

Examples

The following example demonstrates how to add an object to the cache asynchronously, with registering a Task to monitor the status of the operation.

ICache cache = CacheManager.GetCache("demoClusteredCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

string key = "Product0";

cache.AddAsync(key, product).ContinueWith(task => OnItemAdded(key, task));

private static void OnItemAdded(string key, Task<CacheItemVersion> task)
{
    if (task.Status == TaskStatus.RanToCompletion)
    {
    ...
    }
    if (task.Status == TaskStatus.Faulted)
    {
    ...
    }
    if (task.Exception != null)
    {
    ...
    }
}

AddBulk(IDictionary<String, CacheItem>, WriteThruOptions)

Adds a dictionary of cache keys with CacheItem to the cache with the WriteThruOptions. The CacheItem contains properties to associate with the item, like expiration, dependencies and eviction information.

Declaration
IDictionary<string, Exception> AddBulk(IDictionary<string, CacheItem> items, WriteThruOptions writeThruOptions = null)
Parameters
Type Name Description
System.Collections.Generic.IDictionary<System.String, CacheItem> items

Dictionary of keys and CacheItem. Keys must be unique.

WriteThruOptions writeThruOptions

WriteThruOptions regarding updating data source. This can be WriteThru, WriteBehind or none.

Returns
Type Description
System.Collections.Generic.IDictionary<System.String, System.Exception>

Dictionary of Keys along with Exception that were unable to store in cache.

Examples

The following example demonstrates how to add items in bulk to the cache. These items have absolute expiration of 2 minutes from now and have a high priority.

ICache cache = CacheManager.GetCache("demoClusteredCache");

CacheItem[] cacheItems = new CacheItem[3];

Product product_1 = new Product();
product_1.Id = 1;
product_1.Name = "Chai";

Product product_2 = new Product();
product_2.Id = 2;
product_2.Name = "Chang";

Product product_3 = new Product();
product_3.Id = 2;
product_3.Name = "Aniseed Syrup";

cacheItems[0] = new CacheItem(product_1);
cacheItems[0].Expiration = new Expiration(ExpirationType.Absolute, new TimeSpan(0, 2, 0));
cacheItems[0].Priority = CacheItemPriority.High;

cacheItems[1] = new CacheItem(product_2);
cacheItems[1].Expiration = new Expiration(ExpirationType.Absolute, new TimeSpan(0, 2, 0));
cacheItems[1].Priority = CacheItemPriority.Normal;

cacheItems[2] = new CacheItem(product_3);
cacheItems[2].Expiration = new Expiration(ExpirationType.Absolute, new TimeSpan(0, 2, 0));
cacheItems[2].Priority = CacheItemPriority.Low;

IDictionary<string, CacheItem> items = new Dictionary<string, CacheItem>()
{
    { "Product0",cacheItems[0]},
    { "Product1",cacheItems[1]},
    { "Product2",cacheItems[2]}
}

WriteThruOptions writeThruOptions = new WriteThruOptions(WriteMode.WriteThru, "ProdDataSource1");

cache.AddBulk(items, writeThruOptions);

Clear()

Removes all elements from the ICache.

Declaration
void Clear()
Remarks

In most of the cases this method's implementation is close to O(1).

Examples

The following example demonstrates how to clear the ICache.

ICache cache = CacheManager.GetCache("demoCache");

cache.Clear();

ClearClientCache()

Removes all elements from the client cache.

Declaration
void ClearClientCache()
Examples

The following example demonstrates how to clear the client cache.

ICache cache = CacheManager.GetCache("demoCache");

cache.ClearClientCache();

Contains(String)

Determines whether the cache contains a specific key.

Declaration
bool Contains(string key)
Parameters
Type Name Description
System.String key

The key to locate in the cache.

Returns
Type Description
System.Boolean

True, if the ICache contains an element with the specified key; otherwise, false.

Remarks

In most of the cases this method's implementation is close to O(1).

Note: In a partitioned cluster this operation is an expensive one as it might result in network calls. It is therefore advised to use this property only when required.

Examples

The following example demonstrates how to check for containment of an item in the cache.

ICache cache = CacheManager.GetCache("demoClusteredCache");

if(cache.Contains("Product0"))
{
    Console.WriteLine("Item found!");
}
Exceptions
Type Condition
System.ArgumentNullException

Key contains a null reference.

System.ArgumentException

Key is not serializable.

ContainsBulk(IEnumerable<String>)

Determines whether the cache contains specifiec keys.

Declaration
IDictionary<string, bool> ContainsBulk(IEnumerable<string> keys)
Parameters
Type Name Description
System.Collections.Generic.IEnumerable<System.String> keys

IEnumerable collection of keys.

Returns
Type Description
System.Collections.Generic.IDictionary<System.String, System.Boolean>

Dictionary of Keys with flag to dertermine presence of each key in cache. True if the ICache contains an element with the specified key; otherwise, false.

Remarks

Note: In a partitioned cluster this operation is an expensive one as it might result in network calls. It is, therefore, advised to use this property only when required.

Examples

The following example demonstrates how to check for containment of an item in the ICache.

ICache cache = CacheManager.GetCache("demoCache");

List<string> keys = new List<string>()
{
    "Product0",
    "Product1"
};

IDictionary<string, bool> result = cache.ContainsBulk(list);
Exceptions
Type Condition
System.ArgumentNullException

Keys contain a null reference.

System.ArgumentException

Keys are not serializable.

Get<T>(String, ref CacheItemVersion, ReadThruOptions)

Retrieves the specified item from the cache object, with read-through caching option available. If the option of read-through has been set, the object will be fetched from the data source if it does not exist in cache. It accepts the CacheItemVersion by reference.

If null is passed for CacheItemVersion, then the version of the object from the cache is returned. If non-null CacheItemVersion is passed, then object is returned from the cache only if that is the current version of the object in the cache.

Declaration
T Get<T>(string key, ref CacheItemVersion version, ReadThruOptions readThruOptions = null)
Parameters
Type Name Description
System.String key

Unique identifier for the cache item to be retrieved.

CacheItemVersion version

The version of the object.

ReadThruOptions readThruOptions

ReadThruOptions to read from data source. These can be either ReadThru, ReadThruForced or none.

Returns
Type Description
T

The retrieved cache item, or a null reference if the key is not found.

Type Parameters
Name Description
T

Specifies the type of value obtained from the cache.

Examples

The following example demonstrates how to retrieve the value cached with ReadThruOptions and version.

ICache cache = CacheManager.GetCache("demoCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

string key = "Product0";

CacheItemVersion version = cache.Add(key, product);

ReadThruOptions readThruOptions = new ReadThruOptions(ReadMode.ReadThru);

Product product = cache.Get<Product>(key,ref version, readThruOptions);

Get<T>(String, ReadThruOptions)

Retrieves the specified item from the cache object, with read-through caching option available. If the option of read-through has been set, the object will be fetched from the data source if it does not exist in cache.

Declaration
T Get<T>(string key, ReadThruOptions readThruOptions = null)
Parameters
Type Name Description
System.String key

The unique identifier for the cache item to be retrieved.

ReadThruOptions readThruOptions

ReadThruOptions to read from data source. These can be either ReadThru, ReadThruForced or none.

Returns
Type Description
T

The retrieved cache item, or a null reference if the key is not found.

Type Parameters
Name Description
T

Specifies the type of value obtained from the cache.

Remarks

If the key does not exists in the cache, then a null value is returned.

Examples

The following example demonstrates how to retrieve the value from the cache.

ICache cache = CacheManager.GetCache("demoClusteredCache");

string key = "Product0";

ReadThruOptions readThruOptions = new ReadThruOptions(ReadMode.ReadThru);

Product product = cache.Get<Product>(key,readThruOptions);
Exceptions
Type Condition
System.ArgumentNullException

Key contains a null reference.

System.ArgumentException

Key is an empty string.

Get<T>(String, Boolean, TimeSpan, ref LockHandle)

Retrieves the specified object from the cache and locks it simulataneously, if it is not already locked. It returns null, if the object is already locked. This is different from the basic Get operation, where an object is returned ignoring the lock altogether. Use this method if you're using NCache item locking features.

Declaration
T Get<T>(string key, bool acquireLock, TimeSpan lockTimeout, ref LockHandle lockHandle)
Parameters
Type Name Description
System.String key

Unique identifier for the cache item to be retrieved.

System.Boolean acquireLock

A flag to determine whether to acquire a lock or not.

System.TimeSpan lockTimeout

The TimeSpan after which the lock is automatically released.

LockHandle lockHandle

An instance of LockHandle to hold the lock information.

Returns
Type Description
T

The retrieved cache item, or a null reference if the key is not found.

Type Parameters
Name Description
T

Specifies the type of value obtained from the cache.

Examples

The following example demonstrates how to retrieve the cached value and acquire a lock at the same time for minutes.

ICache cache = CacheManager.GetCache("demoCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

string key = "Product0";

cache.Add(key, product);

LockHandle lockHandle = new LockHandle();

object cachedItem = cache.Get<Product>(key, true, new TimeSpan(0, 2, 0), ref lockHandle);
Exceptions
Type Condition
System.ArgumentNullException

key contains a null reference.

System.ArgumentException

key is an empty string.

GetBulk<T>(IEnumerable<String>, ReadThruOptions)

Retrieves the objects from cache for the given keys as key-value pairs. Options regarding reading from data source (read-through) can be set.

Declaration
IDictionary<string, T> GetBulk<T>(IEnumerable<string> keys, ReadThruOptions readThruOptions = null)
Parameters
Type Name Description
System.Collections.Generic.IEnumerable<System.String> keys

The keys against which items are to be fetched from cache.

ReadThruOptions readThruOptions

ReadThruOptions to read from data source. These can be either ReadThru, ReadThruForced or none.

Returns
Type Description
System.Collections.Generic.IDictionary<System.String, T>

The retrieved cache items as key-value pairs.

Type Parameters
Name Description
T

Specifies the type of value obtained from the cache.

Examples

The following example demonstrates how to retrieve the value cached against multiple keys with ReadThruOptions.

ICache cache = CacheManager.GetCache("demoClusteredCache");

List<string> keys = new List<string>()
{
    "Product0",
    "Product1",
    "Product2"
};

ReadThruOptions readThruOptions = new ReadThruOptions(ReadMode.ReadThru);

IDictionary<string, Product> items = cache.GetBulk<Product>(keys, readThruOptions);
Exceptions
Type Condition
System.ArgumentNullException

Keys contain a null reference.

System.ArgumentException

Keys cannot be serialized.

GetCacheItem(String, ref CacheItemVersion, ReadThruOptions)

Retrieves the specified CacheItem from the cache object. This overload also allows specifying the ReadThruOptions. If read-through is set and the object does not exist in the cache, the object will be fetched from the data source and added to the cache. It accepts the CacheItemVersion by reference.

If null is passed for CacheItemVersion, then the version of the object from the cache is returned. If non-null CacheItemVersion is passed, then object is returned from the cache only if that is the current version of the object in the cache.

Declaration
CacheItem GetCacheItem(string key, ref CacheItemVersion version, ReadThruOptions readThruOptions = null)
Parameters
Type Name Description
System.String key

Unique identifier for the cache item to be retrieved.

CacheItemVersion version

The CacheItemVersion of the object.

ReadThruOptions readThruOptions

Options regarding reading from data source. It can be either ReadThru or none.

Returns
Type Description
CacheItem

The specified CacheItem. If the key does not exist, it returns a null reference.

Examples

The following example demonstrates how to retrieve the CacheItem with ReadThruOptions and CacheItemVersion.

ICache cache = CacheManager.GetCache("demoClusteredCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

string key = "Product0";

CacheItemVersion version = cache.Add(key, product);

ReadThruOptions readThruOptions = new ReadThruOptions(ReadMode.ReadThru);

CacheItem item = cache.GetCacheItem(key, ref version, readThruOptions);
Exceptions
Type Condition
System.ArgumentNullException

key contains a null reference.

GetCacheItem(String, ReadThruOptions)

Retrieves the specified CacheItem from the cache object. This overload also allows specifying the ReadThruOptions. If read-through is set and the object does not exist in the cache, the object will be fetched from the data source and added to the cache.

Declaration
CacheItem GetCacheItem(string key, ReadThruOptions readThruOptions = null)
Parameters
Type Name Description
System.String key

Unique identifier for the cache item to be retrieved.

ReadThruOptions readThruOptions

ReadThruOptions regarding reading from data source. It can be either ReadThru, ReadThruForced or none.

Returns
Type Description
CacheItem

The specified CacheItem. If the key does not exist, it returns a null reference.

Examples

The following example demonstrates how to retrieve the cache item with ReadThruOptions and CacheItemVersion.

ICache cache = CacheManager.GetCache("demoClusteredCache");
string key = "Product0";
ReadThruOptions readThruOptions = new ReadThruOptions(ReadMode.ReadThru);
CacheItem cacheItem = cache.GetCacheItem(key, readThruOptions);
Exceptions
Type Condition
System.ArgumentNullException

Key contains a null reference.

GetCacheItem(String, Boolean, TimeSpan, ref LockHandle)

Retrieves the cache item from the cache and locks it if it is not already locked. If the item is already locked, it returns null. This differs from the basic GetCachItem operation, which returns an item (while ignoring the lock). If you're using the NCache item locking features, use this approach.

Declaration
CacheItem GetCacheItem(string key, bool acquireLock, TimeSpan lockTimeout, ref LockHandle lockHandle)
Parameters
Type Name Description
System.String key

Key used to reference the desired object.

System.Boolean acquireLock

A flag to determine whether to acquire a lock or not.

System.TimeSpan lockTimeout

The TimeSpan after which the lock is automatically released.

LockHandle lockHandle

An instance of LockHandle to hold the lock information.

Returns
Type Description
CacheItem

The retrieved cache item. If key is not found, a null reference.

Examples

The following example demonstrates how to retrieve the cache item with lock handle, timeout and flag for aquiring a lock.

ICache cache = CacheManager.GetCache("demoClusteredCache");
string key = "Product0";
LockHandle lockHandle = new LockHandle();
CacheItem item = cache.GetCacheItem(key, true, TimeSpan.FromSeconds(30), ref lockHandle);

GetCacheItemBulk(IEnumerable<String>, ReadThruOptions)

Retrieves the specified CacheItems from the cache object. This overload also allows specifying the ReadThruOptions. If read-through is set and the object does not exist in the cache, the object will be fetched from the data source and added to the cache.

Declaration
IDictionary<string, CacheItem> GetCacheItemBulk(IEnumerable<string> keys, ReadThruOptions readThruOptions = null)
Parameters
Type Name Description
System.Collections.Generic.IEnumerable<System.String> keys

IEnumerable list of unique identifiers for the cache items to be retrieved.

ReadThruOptions readThruOptions

ReadThruOptions regarding reading from data source. It can be either ReadThru, ReadThruForced or none.

Returns
Type Description
System.Collections.Generic.IDictionary<System.String, CacheItem>

The retrieved cache items as key-value pairs.

Examples

The following example demonstrates how to retrieve the cache items with ReadThruOptions.

ICache cache = CacheManager.GetCache("demoClusteredCache");

List<string> keys = new List<string>()
{
    "Product0",
    "Product1",
    "Product2"
};

ReadThruOptions readThruOptions = new ReadThruOptions(ReadMode.ReadThru);
IDictionary<string, CacheItem> items = cache.GetCacheItemBulk(keys, readThruOptions);

GetCacheStream(String, CacheStreamAttributes)

Gets a CacheStream instance.

Declaration
CacheStream GetCacheStream(string key, CacheStreamAttributes cacheStreamAttributes = null)
Parameters
Type Name Description
System.String key

The key used to reference the stream.

CacheStreamAttributes cacheStreamAttributes

Instance of CacheStreamAttributes to set attributes of the stream.

Returns
Type Description
CacheStream

An instance of CacheStream.

Examples

The following example demonstrates how to get the cache stream with Stream mode, Expiration and Cache Item Priority. box server control.

ICache cache = CacheManager.GetCache("demoClusteredCache");

string key = "Product1";

CacheStreamAttributes cacheStreamAttributes = new CacheStreamAttributes(StreamMode.ReadWithoutLock);
cacheStreamAttributes.CacheItemPriority = CacheItemPriority.Normal;
cacheStreamAttributes.Expiration = new Expiration(ExpirationType.None);

cache.GetCacheStream("abc", cacheStreamAttributes);

GetIfNewer<T>(String, ref CacheItemVersion)

Gets an object from the cache only if a newer version of the object exists in cache.

Declaration
T GetIfNewer<T>(string key, ref CacheItemVersion version)
Parameters
Type Name Description
System.String key

Unique key used to reference the desired object.

CacheItemVersion version

The version of the specified object passed by reference.

Returns
Type Description
T

If a newer object exists in the cache, the object is returned. Otherwise, null is returned.

Type Parameters
Name Description
T

Specifies the type of value obtained from the cache.

Examples

The following example demonstrates how to get a newer version of the item from cache if it exists.

ICache cache = CacheManager.GetCache("demoCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

string key = "Product0";

CacheItemVersion version = cache.Add(key, product);

Product product = cache.GetIfNewer<Product>(key, ref version);

GetJsonEnumerator()

Retrieves a dictionary enumerator used to iterate through the key settings and their values as JSON objects contained in the cache.

Declaration
IEnumerator GetJsonEnumerator()
Returns
Type Description
System.Collections.IEnumerator

An enumerator to iterate through the Alachisoft.NCache.Client.Cache as JSON objects.

Remarks

To use GetJsonEnumerator method, cache serilization must be set to JSON instead of Binary.

Note: Just like Alachisoft.NCache.Client.Cache.Count in a cluster, especially a partitioned cluster, this operation is an expensive one and may require network calls. It is, therefore, advised to use this method only when required.

Insert(String, CacheItem, LockHandle, Boolean)

Inserts a CacheItem into the cache.

Declaration
CacheItemVersion Insert(string key, CacheItem item, LockHandle lockHandle, bool releaseLock)
Parameters
Type Name Description
System.String key

Unique key to identify the cache item.

CacheItem item

The CacheItem that is to be inserted into the cache.

LockHandle lockHandle

An instance of LockHandle that holds the lock information. If the item is locked, then it can only be updated if the correct lockHandle is specified.

System.Boolean releaseLock

A flag to determine whether or not the lock should be released after operation is performed.

Returns
Type Description
CacheItemVersion

Represents the version of each cache item.

Remarks

If the key already exists, this overload overwrites the values of the existing ICache item. If the key does not exist, it adds the item to the cache. If CacheItem contains invalid values the related exception is thrown. See CacheItem for invalid property values and related exceptions.

Examples

The following example demonstrates how to insert an item to the cache with a sliding expiration of 5 minutes, a priority of high.

ICache cache = CacheManager.GetCache("demoClusteredCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

CacheItem item = new CacheItem(product);
item.Priority = CacheItemPriority.Low;

string key = "Product0";

cache.Add(key, item);

LockHandle lockHandle = new LockHandle();

CacheItem cachedItem = cache.Get<CacheItem>("cachedItemKey", true, new TimeSpan(0, 5, 0), ref lockHandle);

if (cachedItem != null)
{
    try
    {
       cachedItem.Priority = CacheItemPriority.High;
       cachedItem.Expiration = new Expiration(ExpirationType.Sliding, new TimeSpan(0, 2, 0));

       cache.Insert(key, cachedItem,  lockHandle, true);
    }
    catch (OperationFailedException ex)
    {
    ...
    }
}

Insert(String, CacheItem, WriteThruOptions, LockHandle, Boolean)

Inserts a CacheItem into the cache, along with allowing to specify the WriteThruOptions.

Declaration
CacheItemVersion Insert(string key, CacheItem item, WriteThruOptions writeThruOptions = null, LockHandle lockHandle = null, bool releaseLock = false)
Parameters
Type Name Description
System.String key

Unique key to identify the CacheItem.

CacheItem item

The CacheItem that is to be inserted into the cache.

WriteThruOptions writeThruOptions

WriteThruOptions regarding updating the data source. This can be either WriteThru, WriteBehind or none.

LockHandle lockHandle

An instance of LockHandle that holds the lock information. If the item is locked, then it can only be updated if the correct lockHandle is specified.

System.Boolean releaseLock

A flag to determine whether or not the lock should be released, after operation is performed.

Returns
Type Description
CacheItemVersion

Represents the version of each cache item.

Remarks

If the key already exists, this overload overwrites the values of the existing ICache item. If the key does not exist, it adds the item to the cache. If CacheItem contains invalid values the related exception is thrown. The functionality of lockhandle with WriteThru is not supported. See CacheItem for invalid property values and related exceptions.

Examples

The following example demonstrates how to insert an item to the cache with a sliding expiration of 5 minutes and a high priority.

ICache cache = CacheManager.GetCache("demoClusteredCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

CacheItem item = new CacheItem(product);
item.Priority = CacheItemPriority.Low;

string key = "Product0";

cache.Add(key, item);

LockHandle lockHandle = new LockHandle();

CacheItem cachedItem = cache.Get<CacheItem>("cachedItemKey", true, new TimeSpan(0, 5, 0), ref lockHandle);

if (cachedItem != null)
{
    try
    {
       cachedItem.Priority = CacheItemPriority.High;
       cachedItem.Expiration = new Expiration(ExpirationType.Sliding, new TimeSpan(0, 2, 0));

       WriteThruOptions writeThruOptions = new WriteThruOptions(WriteMode.WriteThru, "ProdDataSource1");

       cache.Insert(key, cachedItem, writeThruOptions, lockHandle, true);
    }
    catch (OperationFailedException ex)
    {
    ...
    }
}

Insert(String, Object)

Inserts an item (object) into the cache.

Declaration
CacheItemVersion Insert(string key, object value)
Parameters
Type Name Description
System.String key

Unique key to identify the cache item.

System.Object value

The item (object) that is to be inserted into the cache.

Returns
Type Description
CacheItemVersion

Represents the version of each cache item.

Remarks

If the key already exists, this overload overwrites the values of the existing ICache item. If the key does not exist, it adds the item to the cache.

Examples

The following example demonstrates how to insert an item (object) into the cache.

Cache cache = CacheManager.GetCache("demoClusteredCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

string key = "Product0";

cache.Insert(key,product);

InsertAsync(String, CacheItem, WriteThruOptions)

Inserts a CacheItem into the cache asynchronously, with a cache key to reference its location and WriteThruOptions.

Declaration
Task<CacheItemVersion> InsertAsync(string key, CacheItem item, WriteThruOptions writeThruOptions = null)
Parameters
Type Name Description
System.String key

Unique key to identify the cache item.

CacheItem item

CacheItem that is to be stored in the cache.

WriteThruOptions writeThruOptions

WriteThruOptions regarding updating the data source. This can be either WriteThru, WriteBehind or none.

Returns
Type Description
System.Threading.Tasks.Task<CacheItemVersion>

Task that performs an insert operation in the background. Once completed returns version of cache item that was added in cache. Task Status property can be used to determine status of the Task that can be IsCanceled, IsCompleted, and IsFaulted.

Examples

The following example demonstrates how to add an CacheItem to the cache asynchronously with registering a Task to monitor the status of the operation along with WriteThruOptions.

ICache cache = CacheManager.GetCache("demoClusteredCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

CacheItem item = new CacheItem(product);

string key = "Product0";

WriteThruOptions writeThruOptions = new WriteThruOptions(WriteMode.WriteThru, "ProdDataSource1");

cache.InsertAsync(key, item, writeThruOptions).ContinueWith(task => OnItemInserted(key, task));

private static void OnItemInserted(string key, Task<CacheItemVersion> task)
{
    if (task.Status == TaskStatus.RanToCompletion)
    {
    ...
    }
    if (task.Status == TaskStatus.Faulted)
    {
    ...
    }
    if (task.Exception != null)
    {
    ...
    }
}

InsertAsync(String, Object)

Inserts an object into the cache asynchronously, with a cache key to reference its location.

Declaration
Task<CacheItemVersion> InsertAsync(string key, object value)
Parameters
Type Name Description
System.String key

Unique key to identify the cache item.

System.Object value

The item (object) to be stored in the cache.

Returns
Type Description
System.Threading.Tasks.Task<CacheItemVersion>

Task that performs an insert operation in the background. Once completed, returns a version of CacheItem that was added in cache. Task Status property can be used to determine status of the Task that can be IsCanceled, IsCompleted, and IsFaulted.

Remarks

If the key already exists, this overload overwrites the values of the existing ICache item. If the key does not exist, it adds the item to the cache.

Examples

The following example demonstrates how to add an object to the cache asynchronously, with registering a Task to monitor the status of the operation.

ICache cache = CacheManager.GetCache("demoClusteredCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

string key = "Product0";

cache.InsertAsync(key, product).ContinueWith(task => OnItemInserted(key, task));

private static void OnItemInserted(string key, Task<CacheItemVersion> task)
{
    if (task.Status == TaskStatus.RanToCompletion)
    {
    ...
    }
    if (task.Status == TaskStatus.Faulted)
    {
    ...
    }
    if (task.Exception != null)
    {
    ...
    }
}

InsertBulk(IDictionary<String, CacheItem>, WriteThruOptions)

Inserts a dictionary of cache keys with CacheItem to the cache with the WriteThruOptions. The CacheItem contains properties to associate with the item, like expiration, dependencies and eviction information.

Declaration
IDictionary<string, Exception> InsertBulk(IDictionary<string, CacheItem> items, WriteThruOptions writeThruOptions = null)
Parameters
Type Name Description
System.Collections.Generic.IDictionary<System.String, CacheItem> items

Dictionary of keys and CacheItem. Keys must be unique.

WriteThruOptions writeThruOptions

WriteThruOptions regarding updating data source. This can be WriteThru, WriteBehind or none.

Returns
Type Description
System.Collections.Generic.IDictionary<System.String, System.Exception>

Dictionary of keys along with exception that were unable to store in cache.

Remarks

If the key or multilple keys already exist, this overload overwrites the values of the existing ICache items. If the key does not exist, it adds the item to the cache.

Examples

The following example demonstrates how to insert items to the cache with an absolute expiration of 2 minutes from now, a priority of high.

ICache cache = CacheManager.GetCache("demoClusteredCache");

CacheItem[] cacheItems = new CacheItem[3];

Product product_1 = new Product();
product_1.Id = 1;
product_1.Name = "Chai";

Product product_2 = new Product();
product_2.Id = 2;
product_2.Name = "Chang";

Product product_3 = new Product();
product_3.Id = 2;
product_3.Name = "Aniseed Syrup";

cacheItems[0] = new CacheItem(product_1);
cacheItems[0].Expiration = new Expiration(ExpirationType.Absolute, new TimeSpan(0, 2, 0));
cacheItems[0].Priority = CacheItemPriority.High;

cacheItems[1] = new CacheItem(product_2);
cacheItems[1].Expiration = new Expiration(ExpirationType.Absolute, new TimeSpan(0, 2, 0));
cacheItems[1].Priority = CacheItemPriority.Normal;

cacheItems[2] = new CacheItem(product_3);
cacheItems[2].Expiration = new Expiration(ExpirationType.Absolute, new TimeSpan(0, 2, 0));
cacheItems[2].Priority = CacheItemPriority.Low;

IDictionary<string, CacheItem> items = new Dictionary<string, CacheItem>()
{
    { "Product0",cacheItems[0]},
    { "Product1",cacheItems[1]},
    { "Product2",cacheItems[2]}
}

WriteThruOptions writeThruOptions = new WriteThruOptions(WriteMode.WriteThru, "ProdDataSource1");

cache.InsertBulk(items, writeThruOptions);

Lock(String, TimeSpan, out LockHandle)

Acquires a lock on an item in the cache.

Declaration
bool Lock(string key, TimeSpan lockTimeout, out LockHandle lockHandle)
Parameters
Type Name Description
System.String key

Key of cached item to be locked.

System.TimeSpan lockTimeout

An instance of System.TimeSpan after which the lock is automatically released.

LockHandle lockHandle

An instance of LockHandle that will be filled in with the lock information, if lock is acquired successfully.

Returns
Type Description
System.Boolean

Whether or not lock was acquired successfully.

Examples

The following example demonstrates how to lock a cached item.

ICache cache = CacheManager.GetCache("demoCache");
string key = "Product0";

LockHandle lockHandle = new LockHandle();

bool locked = cache.lock(key, new TimeSpan(0,0,10), out lockHandle);

Remove(String, LockHandle, CacheItemVersion, WriteThruOptions)

Removes the specified item from the ICache. You can also specify the write option, such that the item may be removed from both cache and data source. If version is specified, then item will only be removed if the specified version is still the most recent version in the cache.

Declaration
void Remove(string key, LockHandle lockHandle = null, CacheItemVersion version = null, WriteThruOptions writeThruOptions = null)
Parameters
Type Name Description
System.String key

Unique key of the item to be removed.

LockHandle lockHandle

If the item is locked, it can be removed only if the correct lockHandle is specified. lockHandle should be the same which was used initially to lock the item, otherwise you will get the 'OperationFailedException'.

CacheItemVersion version

The version of the item to be removed. The item is removed from the cache only if this is still the most recent version in the cache.

WriteThruOptions writeThruOptions

WriteThruOptions regarding updating the data source. This can be either WriteThru, WriteBehind or none.

Examples

The following example demonstrates how to remove a locked item in the cache with WriteThruOptions.

ICache cache = CacheManager.GetCache("demoCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

string key = "Product0";

CacheItemVersion version = cache.Add(key, product);

LockHandle lockHandle = new LockHandle();

object item = cache.Get<Product>(key, true, TimeSpan.Zero, ref lockHandle);

if (item != null)
{
    try
    {
        WriteThruOptions writeThruOptions = new WriteThruOptions(WriteMode.WriteThru, "ProdDataSource1");

        cache.Remove(key, lockHandle, version, writeThruOptions);
    }
    catch (OperationFailedException ex)
    {
    ...
    }
}

Remove<T>(String, out T, LockHandle, CacheItemVersion, WriteThruOptions)

Removes the specified item from the ICache and returns it to the application as an out parameter. You can also specify the write option such that the item may be removed from both cache and data source. If version is specified, then item will only be removed if the specified version is still the most recent version in the cache.

Declaration
bool Remove<T>(string key, out T removedItem, LockHandle lockHandle = null, CacheItemVersion version = null, WriteThruOptions writeThruOptions = null)
Parameters
Type Name Description
System.String key

Unique key of the item to be removed.

T removedItem

Out parameter through which the removed item from cache is returned

LockHandle lockHandle

If the item is locked, it can be removed only if the correct LockHandle is specified. LockHandle should be the same which was used initially to lock the item, otherwise you will get the 'OperationFailedException'.

CacheItemVersion version

The version of the item to be removed. The item is removed from the cache, only if this is still the most recent version in the cache.

WriteThruOptions writeThruOptions

WriteThruOptions regarding updating the data source. This can be either WriteThru, WriteBehind or none.

Returns
Type Description
System.Boolean

Flag which determines the status of remove operation. True if item was removed successfully from the cache or False if remove opeartaion failed.

Type Parameters
Name Description
T

Specifies the type of value obtained from the cache.

Examples

The following example demonstrates how you can remove an item from the cache.

ICache cache = CacheManager.GetCache("demoCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

string key = "Product0";

CacheItemVersion version = cache.Add(key, product);

LockHandle lockHandle = new LockHandle();
object item = cache.Get<Product>(key, true, TimeSpan.Zero, ref lockHandle);

WriteThruOptions writeThruOptions = new WriteThruOptions(WriteMode.WriteThru, "ProdDataSource1");

try
{
    Product removedProduct = null;
    if (cache.Remove<Product>(key, out removedProduct, lockHandle, version, writeThruOptions))
    {
        //Removed successfully
    }
    else
    {
        //Error Occured
    }
}
catch(Exception ex)
{
...
}
Exceptions
Type Condition
System.ArgumentNullException

Key contains a null reference.

System.ArgumentException

Key is not serializable.

RemoveAsync<T>(String, WriteThruOptions)

Removes an item from the cache asynchronously, with a cache key to reference its location and WriteThruOptions.

Declaration
Task<T> RemoveAsync<T>(string key, WriteThruOptions writeThruOptions = null)
Parameters
Type Name Description
System.String key

Unique key of the item to be removed.

WriteThruOptions writeThruOptions

WriteThruOptions regarding updating the data source. This can be either WriteThru, WriteBehind or none.

Returns
Type Description
System.Threading.Tasks.Task<T>

Task that performs a remove operation in the background. Once completed returns the item that was removed from the cache. Task Status property can be used to determine status of the Task that can be IsCanceled, IsCompleted, and IsFaulted.

Type Parameters
Name Description
T

Specifies the type of value obtained from the cache.

Examples

The following example demonstrates how you can remove an item from your application's Alachisoft.NCache.Client.Cache object asynchronously.

ICache cache = CacheManager.GetCache("demoClusteredCache");

string key = "Product0";

WriteThruOptions writeThruOptions = new WriteThruOptions(WriteMode.WriteThru, "ProdDataSource1");

cache.RemoveAsync<Product>(key, writeThruOptions).ContinueWith(task => OnItemRemoved(key, task));

private static void OnItemRemoved(string key, Task<Product> task)
{
    if (task.Status == TaskStatus.RanToCompletion)
    {
    ...
    }
    if (task.Status == TaskStatus.Faulted)
    {
    ...
    }
    if (task.Exception != null)
    {
    ...
    }
}

RemoveBulk(IEnumerable<String>, WriteThruOptions)

Removes the specified items from the ICache. You can also specify the write option such that the items may be removed from both cache and data source.

Declaration
void RemoveBulk(IEnumerable<string> keys, WriteThruOptions writeThruOptions = null)
Parameters
Type Name Description
System.Collections.Generic.IEnumerable<System.String> keys

List of unique keys to reference the items.

WriteThruOptions writeThruOptions

WriteThruOptions regarding updating the data source. This can be either WriteThru, WriteBehind or none.

Examples

The following example demonstrates how you can remove an item from your application's ICache object.

ICache cache = CacheManager.GetCache("demoClusteredCache");

List<string> keys = new List<string>()
{
    "Product0",
    "Product1",
    "Product2"
};

WriteThruOptions writeThruOptions = new WriteThruOptions(WriteMode.WriteThru, "ProdDataSource1");

cache.RemoveBulk(keys, writeThruOptions);
Exceptions
Type Condition
System.ArgumentNullException

Keys contain a null reference.

System.ArgumentException

Keys are not serializable.

RemoveBulk<T>(IEnumerable<String>, out IDictionary<String, T>, WriteThruOptions)

Removes the specified items from the Alachisoft.NCache.Client.Cache and returns them to the application in the form of a dictionary as an out Parameter.

Declaration
void RemoveBulk<T>(IEnumerable<string> keys, out IDictionary<string, T> removedItems, WriteThruOptions writeThruOptions = null)
Parameters
Type Name Description
System.Collections.Generic.IEnumerable<System.String> keys

List of unique keys to reference the items.

System.Collections.Generic.IDictionary<System.String, T> removedItems

out Parameter through which the removed items from the cache are returned.

WriteThruOptions writeThruOptions

WriteThruOptions regarding updating the data source. This can be either WriteThru, WriteBehind or none.

Type Parameters
Name Description
T

Specifies the type of value obtained from the cache.

Remarks

RemovedItems dictionary contains the key and value of the items that were successfully removed from the cache.

Examples

The following example demonstrates how you can remove multiple of items from your application's ICache object.

ICache cache = CacheManager.GetCache("demoClusteredCache");

List<string> keys = new List<string>()
{
    "Product0",
    "Product1",
    "Product2"
};

WriteThruOptions writeThruOptions = new WriteThruOptions(WriteMode.WriteThru, "ProdDataSource1");

IDictionary<string, Product> products = null;
cache.RemoveBulk<Product>(keys,out products);
Exceptions
Type Condition
System.ArgumentNullException

keys contains a null reference.

System.ArgumentException

keys is not serializable.

Unlock(String, LockHandle)

Unlocks a locked cached item, if the correct LockHandle is specified. If LockHandle is null, it forcefully unlocks a locked cached item.

Declaration
void Unlock(string key, LockHandle lockHandle = null)
Parameters
Type Name Description
System.String key

Key of the cached item to be unlocked.

LockHandle lockHandle

An instance of LockHandle that is generated when the lock is acquired.

Examples

The following example demonstrates how to unlock a cached item.

ICache cache = CacheManager.GetCache("demoCache");
string key = "Product0";

cache.Unlock(key, lockHandle);

UpdateAttributes(String, CacheItemAttributes)

Update CacheItemAttributes of an existing item in cache.

Declaration
bool UpdateAttributes(string key, CacheItemAttributes attributes)
Parameters
Type Name Description
System.String key

Unique key to identify the cache item.

CacheItemAttributes attributes

An instance ofCacheItemAttributes to update item in the cache.

Returns
Type Description
System.Boolean

Flag that determines status of the update operation. True if attributes of the item in cache was updated successfully otherwise False.

Examples

The following example demonstrates how to update absolute expiration of 5 minutes on an existing item in cache.

ICache cache = CacheManager.GetCache("demoCache");

Product product = new Product();
product.Id = 1;
product.Name = "Chai";

string key = "Product0";

cache.Insert(key, product);

CacheItemAttributes attributes = new CacheItemAttributes();
attributes.AbsoluteExpiration = DateTime.Now.AddMinutes(5);

if(cache.UpdateAttributes(key, attributes))
{
...
}

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Community
  • 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 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top