A
A
Alexey Lebedev2014-10-10 13:22:21
SQL
Alexey Lebedev, 2014-10-10 13:22:21

How to use CacheDependency in ASP.NET?

I use so cache.

Cache.Get("prefix_"+xxx+"_"+yyyy);
Cache.Insert("prefix_"+xxx+"_"+yyyy, data, null, DateTime.Now.AddSeconds(1), Cache.NoSlidingExpiration, CacheItemPriority.High, null);

This significantly reduced the load on the database.
But the data changes frequently and re-getting it every 1 second is not entirely correct.
There is a script responsible for updating. When I run it, then all yyyy, at a certain xxx, become irrelevant.
An example of information in the cache.
prefix_1000_34
prefix_1000_36
prefix_1000_37
prefix_1000_39
prefix_1000_51
prefix_2000_34
prefix_2000_39
prefix_2004_18
prefix_2004_25
prefix_2004_48

When requesting with parameter 2000, only: prefix_2000_34, prefix_2000_39 become irrelevant. The rest do not lose their power.
I have seen CacheDependency which depend on the DB or on the file, but I don't need it.
It is necessary for me that at one fine moment some set of data in the cache is made irrelevant.
I have no idea how to highlight them.
The only thing that came to my mind was to use the file and change it when the data becomes out of date.
But I think there is a more normal option.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Glebov, 2014-10-10
@swanrnd

Try like this
1. Your CacheDependency

class CustomDependencyManager {
  class CustomDependency : CacheDependency {
    public void Invalidate() {
      NotifyDependencyChanged(this, EventArgs.Empty);
     }
  }
  public static CustomDependencyManager Instance = new CustomDependencyManager();

  private readonly ConcurrentDictionary<string, CustomDependency> dependencies = new ConcurrentDictionary<string, CustomDependency>();

  private CustomDependency GetCacheDependencyInternal(string xxx) {
    return dependencies.GetOrAdd(xxx, s => new CustomDependency());
  }

  public void Invalidate(string xxx) {
    GetCacheDependencyInternal(xxx).Invalidate();
  }
  
  public CacheDependency For(string xxx) {
    GetCacheDependencyInternal(xxx);            
  }
}

2. When necessary, reset the cache
Cache.Insert("prefix_"+xxx+"_"+yyyy, data, CustomDependencyManager.Instance.For(xxx), DateTime.Now.AddSeconds(1), Cache.NoSlidingExpiration, CacheItemPriority.High, null);

...
...
// Пора сбросить кеш 
CustomDependencyManager.Instance.Invalidate(xxx);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question