• Webinars
  • Docs
  • Download
  • Blogs
  • Contact Us
Show / Hide Table of Contents
  • Programmer's Guide
  • Client Side API Programming
    • Setting Up Development Environment
    • Basic Cache Operations
      • Initialize Cache
      • Add Data to Cache
      • Update Data in Cache
      • Fetch Data From Cache
      • Remove Data From Cache
      • Dispose Cache
    • Bulk Operations
      • Adding Collection to Cache
      • Updating Collection in Cache
      • Retrieving Collection from Cache
      • Removing Collection from Cache
      • Deleting Collection from Cache
    • Asynchronous Operations
      • Using Asynchronous Operations
      • Using Asynchronous Operations with Callback Methods
    • Groups and Subgroups
      • Adding/Updating Data Group in Cache
      • Retrieving Data Group from Cache
      • Removing Data Group from Cache
    • Tagging Data in NCache
      • Creating Tags
      • Adding Items with Tags
      • Retrieving Previously Tagged Data
      • Removing Tagged Items from Cache
    • Named Tags
    • Data Expiration Strategies
      • Using Absolute Expiration
      • Using Sliding Expiration
    • Cache Dependencies
      • Key Dependency
      • File Dependency
      • Notification based Dependencies
        • Database Dependency using SQL Server
        • Database Dependency using Oracle
      • Polling Based Dependency
      • Custom Data Source Dependency
      • Multiple Cache Sync Dependency
      • Aggregate Dependency
      • Add Dependency to Existing Item
      • Using CLR Procedures to Call NCache
    • Locking Data in NCache
      • Locking Items in Cache (Pessimistic Locking)
      • Locking Items with Cache Item Versioning (Optimistic Locking)
    • SQL Reference for NCache
      • SQL Syntax
      • Querying Samples for Operators
      • Querying Data in NCache
      • NCache Language Integrated Query (LINQ)
        • Using LINQ in NCache
        • Configuring LINQPad for NCache
        • Querying NCache Data in LINQPad
    • Event Notifications
      • Cache Level Event Notifications
      • Item Level Event Notifications
      • Custom Event Notifications
    • Publish/Subscribe (Pub/Sub) in NCache
      • Pub/Sub Topics
      • Managing Topics
      • Pub/Sub Messages
        • Message Behavior and Properties
        • Creating a Message
      • Publish Messages to Topic
      • Subscribe for Topic Messages
      • Monitoring Pub/Sub Topics
    • Continuous Query
    • Using Streams in NCache
      • Opening with Stream Modes
      • Adding and Updating Data with Streams
      • Retrieving Data from Streams
      • Closing a Stream
    • Security and Encryption
      • NCache Security
      • NCache Data Encryption
    • Data Compression
    • NCache Management API
  • Server Side API Programming
    • Cache Startup Loader
      • Components of Cache Startup Loader
      • Sample Implementation of ICacheLoader on Single Node
      • Sample Implementation of ICacheLoader with Distribution Hints
    • Data Source Providers (Backing Source)
      • Read-Through Caching
        • Configure Read-Through Provider
        • Using Read-Through with Cache Operations
      • Write-Through Caching
        • Configuring Write-Through Provider
        • Using Write-Through with Basic Operations
        • Using Write-Behind with Basic Operations
        • Using Write-Behind with Bulk Operations
        • Using Write-Behind with Async Operations
        • Monitor Write-Through Counters
    • Custom Dependency
      • Sample Implementation of Custom Dependency
      • Sample Usage of Custom Dependency
    • WAN Replication through Bridge
      • Bridge Configurations
      • Implementing Bridge Conflict Resolver
    • Entry Processor
      • Sample Implementation of IEntryProcessor Interface
      • Sample Usage of EntryProcessor
    • MapReduce
      • Sample Implementation of MapReduce Interfaces
      • Sample Usage of MapReduce
    • Aggregator
      • Sample Implementation of IValueExtractor Interface
      • Sample Implementation of IAggregator Interface
      • Sample Usage of Aggregator
    • Dynamic Compact Serialization
  • Client Side ASP.NET Features
    • ASP.NET
      • ASP.NET Session State Provider for NCache
      • Multi-Region ASP.NET Session State Provider for NCache
    • ASP.NET Core
      • Session Storage in ASP.NET Core
        • Configure NCache ASP.NET Core Session Provider
        • Configure ASP.NET Core Sessions with NCache IDistributedCache Provider
      • Multi-Region ASP.NET Core Session Provider for NCache
      • Object Caching in ASP.NET Core
    • ASP.NET SignalR
      • Using NCache Extension for SignalR
    • View State Caching
      • Configuring and Using Content Optimization
      • Group View State with Sessions
      • Limit View State Caching
      • Perform Page Level Grouping for View State
    • ASP.NET Output Cache
      • Configure ASP.NET Output Caching
      • Using ASP.NET Output Cache with Custom Hooks
  • Client Side Third Party Integrations
    • Migrating AppFabric to NCache
      • AppFabric API vs. NCache API
    • NHibernate
      • NCache as NHibernate Second Level Cache
      • Using NHibernate Query Caching
      • Configuring Database Synchronization with NHibernate
    • Entity Framework Caching Integration
      • NCache as Entity Framework Second Level Cache
      • Entity Framework Caching Config File
    • Entity Framework Core Caching
      • Installing NCache Entity Framework Core Provider
      • Configuring NCache Entity Framework Core Provider
      • Using NCache Entity Framework Core Provider
        • Caching Options for EF Core Provider
        • LINQ APIs for EF Core Provider
        • Cache Only APIs for EF Core Provider
        • Query Deferred APIs for EF Core Provider
      • Logging in NCache Entity Framework Core Provider
    • Memcached
      • NCache Memcached Gateway Approach
      • Memcached Client Plugin for .NET
    • Debug NCache Providers in Visual Studio
    • NCache for Visual Studio Extension

Locking Items Using Cache Item Versioning (Optimistic locking)

There are two types of locking available with NCache. For Pessimistic locking, kindly review Pessimistic Locking section.

  • In optimistic locking, NCache uses cache item versioning. CacheItemVersion is a property associated with every cache item. It is basically a numeric value that is used to represent the version of the cached item which changes with every update to an item. This property allows you to track whether any change occurred in an item or not. When you fetch an item from cache, you also fetch its current version in the cache.

  • You can specify the cache item version in data update call. This update call succeeds only if the current version of the cache item is the same as passed by the client, otherwise it fails. This is used when you want to update a cache item which you have previously read from cache. If someone else has updated the cache item, the update should fail. In this way each client will update only the latest copy of the data and hence maintain data integrity throughout the cache.

CacheItemVersion adds an additional dimension to the development of application using NCache. Optimistic concurrency can be achieved in applications by NCache Item Versioning.

When any item is added in cache, cache item version is returned to the cache client. This value denotes the number of updates performed on a particular data. With every update, item version value is incremented.

To utilize the APIs, include the following namespace in your application: Alachisoft.NCache.Web.Caching.

Saving Item Version for the First Time

An Add operation returns CacheItemVersion. If an item is added for the first time, a GUID value containing the timestamp of its creation is returned. This version will be updated accordingly in future operations on this key.

In the following example, you will add a custom data in cache with key Product:1001 and save its item version. Kindly ensure that the object is either serialized or registered with NCache Compact serialization framework.

  Product product = new Product();
  product.ProductID = 1001;
  product.ProductName = "Chai";
  string key = "Product:" + product.ProductID;

  try
  {
      CacheItemVersion itemVersion = cache.Add(key, product);
      //Save this item Version for future utilization  
  }
  catch (OperationFailedException ex)
  {
      // handle exception
  }

Updating Item with Specific Version

Item versioning can be used to ensure consistency of data in an environment where the cache is being accessed by multiple applications. The item version can be used to ensure that the data being updated is the same as in the cache and has not been updated prior to the update operation by any other cache client.

In the following example, an update is performed on a previously cached item. If the specified version is equal in the cache item, then it will be updated else an exception will be thrown by NCache.

//precondition: itemVersion is saved when item was added in cache

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;

//saved itemVersion from add item call
cacheItem.Version = itemVersion;
try
{
    CacheItemVersion newVersion = cache.Insert(key, cacheItem);

   //save new version for future usage

   //verify the updated version and value in cache
}
catch (OperationFailedException ex)
{
    // handle exception
}

Retrieving Cached Item with Specific Version

You can retrieve a cached item by specifying the item version. In case of a mismatch of version, “null” value is returned.

In the following example you need to specify the key and its previously saved item version to fetch the cached object.

//precondition: itemVersion is saved when item was added or inserted in cache
try
{
    string key = "Product:1001";

    //saved itemVersion from add or insert item call
    CacheItem result = cache.GetCacheItem(key, ref itemVersion);
    if (result.Value != null)
    {
        if (result.Value is Product)
        {
            Product product = (Product)result.Value;
        }
    }
}
catch (OperationFailedException ex)
{
    // handle exception
}

Retrieve Item if a Newer Version Exists in Cache

GetIfNewer method can be used to fetch the existing item if a newer version is available in cache. By specifying the current version as an argument of the method call, the cache returns appropriate result.

If the version specified is less than the one in cache, only then the method returns a new Item else null would be returned.

  //precondition: itemVersion is saved when item was added or inserted in cache
  string key = "Product:1001";
  try
  {
      //saved itemVersion from add or insert item call
      object result = cache.GetIfNewer(key, ref itemVersion);
      if (result != null)
      {
          if (result is Product)
          {
              Product product = (Product)result;
          }
      }
  }
  catch (OperationFailedException ex)
  {
      // handle exception
  }

Removing an Item with Specified Item Version

The Remove method is a basic method which removes the key from cache and returns the removed object to the cache. If a custom object is added to the cache, the remove method will return Object.

If the item version is different from the one in the cache or if the key does not exist, an OperationFailedException will be thrown by NCache.

  //precondition: itemVersion is saved when item was added or inserted in cache
  string key = "Product:1001";
  try
  {
      //saved itemVersion from add or insert item call
      object result = cache.Remove(key, itemVersion);
      if (result != null)
      {
          if (result is Product)
          {
              Product product = (Product)result;
          }
      }
  }
  catch (OperationFailedException ex)
  {
      // handle exception
  }

Delete an Item with Item Version

A Delete method is a basic method which deletes the key from cache. If the item version is different from the one in the cache or if the key does not exist, an Exception will be thrown by NCache.

//precondition: itemVersion is saved when item was added or inserted in cache
string key = "Product:1001";
try
{
    //saved itemVersion from add or insert item call
    cache.Delete(key, itemVersion);
}
catch (OperationFailedException ex)
{
    // handle exception
}
Back to top Copyright © 2017 Alachisoft