In the following code i want to achieve this: every time a user asks for a specific piece of content, i first check if I already got this content from the DB on the same day.
If so – I shall return the cached content. If not – i first re-retrieve the content from the DB ,return it to the user and cache it for the next requests from this day, and so on ..
What i want to know is if it is a good code practice for saving (a lot of ) DB time on popular content . (I care less about how the code example looks, as just made it up for this question and it’s not going to be used as-is in my app ..)
the code example:
public class ContentCachingExample
{
private static DateTime _lastRequestTime;
private static MyContent _cachedContent;
private static MyContent GetContent()
{
// compare dates - content will be re-retrieved from DB once a day.
if (DateTime.Now.Date> _lastRequestTime.Date)
{
_lastRequestTime = DateTime.Now;
_cachedContent = GetContentFromDb();
}
return _cachedContent;
}
private static MyContent GetContentFromDb()
{
// get content from DB
}
public class MyContent
{
public string Property1 { get; set; }
public int Property2 { get; set; }
}
}
What you are doing is a common pattern.
You should consider some of the libraries that exist, particularly if you ever need to fine-tune the caching mechanism.
David has mentioned System.Web.Cache
There is also Enterprise Library Caching Blocks
However, if you only need the current capabilities of your code, then what you have is fine.