Search code examples
cachingappfabric

How to deal with data contention in AppFabric under the optimistic concurrency model?


According to this MSDN page, "Put supports optimistic concurrency by taking version information as an optional parameter; Put only succeeds if the object to be replaced is of the same version."

What's a good solution for when the versions do differ? The cache client is a WCF service.


Solution

  • If the versions differ, it's an indication that another client has got in ahead of you and updated the cached object. You can detect this by trapping the DataCacheException that'll be thrown from your call to Put and checking the ErrorCode against the DataCacheErrorCode enum - CacheItemVersionMismatch is the specific entry to test against. Trapping this error is an indication that the cached item your current client is working with is stale, you should probably get the latest version from the client (which you may or may not want to display to a user) before you try making your changes again.

    This is why in an optimistic concurrency scenario you want to get the cached object, make your changes and then return it to the cache as soon as possible - you don't want to be holding a version over any kind of long-running process or you start to see these kinds of problems.