简体   繁体   中英

ASP.NET Data Caching

I have a result set returned from a database that takes a few seconds to run. To increase performance I'm going to cache the results for up to 30 minutes. The call to the database takes a date parameter, a date within the next 60 days that the user selects from a calendar.

Here is a code sample that uses a list of strings to keep the example simple:

public List<String> GetConcertList(DateTime selectedDate)
        {
            String cacheKey;

            cacheKey = "ConcertList" + selectedDate.Date.Ticks.ToString();

            List<String> concertList = HttpContext.Current.Cache[cacheKey] as List<String>;

            if (concertList == null)
            {
                // Normally this is the call to the database that passes the selected date
                concertList.Add("Just a test for " + selectedDate.ToString());

                HttpContext.Current.Cache.Insert(cacheKey, concertList, null, DateTime.Now.AddMinutes(30),
                                                 System.Web.Caching.Cache.NoSlidingExpiration);
            }

            return concertList;
        }

Is there a better approach then using the date in the key to cache each day's list?

How large is the dataset we're talking about here? If it's not huge, you may want to Cache the whole list and then just pull out the subset based on the user's selected date.

A better way to do this would be to keep a master dataset that's an aggregate of all of the user-requested dates. Basically, you would just append any new, not-yet-requested results to your cached dataset and work from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM