5

Is there a way, using Azure Caching, to determine if an object having a specific key exists in cache, without actually returning the object itself?

I'm currently doing something like

    public bool IsKeyInCache(string cacheKey)
    {
        DataCacheItem item = null;
        CacheRetryPolicy.ExecuteAction(() =>
        {
            item = cache.GetCacheItem(cacheKey);
        });

        return item != null;
    }

But, because the object in cache is very large and expensive to deserialize, performance is horrible.

I've dug through the MSDN documentation and don't see any alternative, but maybe I'm missing something.

My best idea so far is to add a small "marker" object to cache at the same time as my large object and check for existence of the "marker" object where deserialization is inexpensive. But this isn't a robust solution, as it's entirely possible for my large object to get purged from cache while the "marker" object remains.

Mr. T
  • 3,892
  • 3
  • 29
  • 48
  • 3
    I'll take a quick stab at why it might not be implemented for any cache in particular ... simply because of a race condition. Between checking to see whether the key exists and reading the value of the key, the item might be evicted from the cache. – ta.speot.is Nov 23 '13 at 12:27
  • Q: Why don't you just ask for the value? Just curious - what's the use case for checking whether or not the key happens to be in cache? – paulsm4 Nov 24 '13 at 07:06

1 Answers1

0

I believe the API you're looking for is DataCache.Get(key):

But I still think you're best bet is to NOT "micro-manage" the cache, just query, and let Azure decide.

IMHO...

Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • DataCache.Get() returns the item if it is in cache. All I want is a yes/no answer as to whether the specified key is in the cache. – Mr. T Nov 25 '13 at 15:06
  • And if it isn't in cache, it returns a NULL. DataCache.Get(key) is honestly your best choice, even for a boolean yes/no. IMHO... – paulsm4 Nov 25 '13 at 18:36
  • 2
    It's my "best choice" because it's my only choice, apparently. Suppose I've cached a very large object. Why pay the price to transfer it out of cache (which may be on a different member of the cluster) and across the network to my role instance, when all I want to know is "does this key exist?" – Mr. T Nov 25 '13 at 21:50