1

I am trying to use caching to save time refreshing my web application and do so automatically whenever the database changes, and am having trouble setting up the cache.

I have added the following code to where I access SQL...

SqlDependency.Start("Data Source=" + serverName + ";" + 
                    "Initial Catalog=...;" + "User Id=...;Password=...;");

and then after the SQL connection is made and just before I pull data from SQL...

SqlCacheDependency dependency = new SqlCacheDependency(command);

int numberOfMinutes = 3;
DateTime expires = DateTime.Now.AddMinutes(numberOfMinutes);

Current.Response.Cache.SetExpires(expires);
Current.Response.Cache.SetCacheability(HttpCacheability.Public);
Current.Response.Cache.SetValidUntilExpires(true);
Current.Response.AddCacheDependency(dependency);

Previously in the method that this code is in, I accessed SQL and returned a list of objects from SQL. What further steps do I need to do to set up the cache? I'm assuming I have to add the data to the cache somehow and then retrieve it from the cache somehow?

1 Answer 1

3

You can use the HttpRuntime.Cache cache object

I would write a generic method to GET and SET cache object.

 public T GetOrSetCache<T>
    (string key,T obj, int cacheTime) where T:class,new()
{
    System.Web.Caching.Cache cacheContainer = HttpRuntime.Cache;
    T cacheObj = cacheContainer.Get(key) as T;

    if (cacheObj == null)
    {
        cacheContainer.Insert(key,
            obj,
            null, 
            DateTime.Now.AddMinutes(cacheTime),
            System.Web.Caching.Cache.NoSlidingExpiration);
        cacheObj = obj;
    }

    return cacheObj;
}

When you want to use cache you can do like this on your main code

var data = [read data from data base]
int numberOfMinutes = 3;
data = GetOrSetCache("name1",data,numberOfMinutes );

HttpRuntime.Cache

NOTE

  1. Cache is a key/value` collection

  2. Get instance from cache you need to provide a key.

  3. Set instance into cache you need to provide a key and instance object.

3
  • Will this cache get automatically updated if I use it like you have described and my SQL table gets updated at some point?
    – Casey Daly
    Jul 9, 2018 at 17:28
  • Unfortunately, I think it is impossible,because cache main intention is keep something in memory if you want to use the data you can get it immediately,that don't have to request db,but your comment request not the same as the main intention of the cache
    – D-Shih
    Jul 9, 2018 at 18:40
  • if your data often update and need data consistency, i will recommend you don't use cache.
    – D-Shih
    Jul 9, 2018 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.