I am using LinQ to XML to populate a dropdown list when my page loads. How can I cache the results so that I don't have to run the query each and every time the page loads? Also the xml file will only be updated once a day. Is it better to cache or just read it each time?
But use the concept from that post (caching is good), not his examples, which are really silly. (Why, in a webserver environment that shares a cache, do you have to dirty the cache via a file???)
James S
2009-08-07 12:12:32
+1
A:
Call ToList()
on the results of the query. Then cache the results in a static variable, accessed in a thread-safe way:
private static List<Whatever> dropDownListValues;
private static object listLock = new object();
public static IList<Whatever> DropDownListValues
{
get
{
lock(listLock)
{
if (dropDownListValues == null ||
DetectValuesChanged()) // However you implement this!
{
dropDownListValues = // insert your query here
.ToList();
}
return dropDownListValues;
}
}
}
Jon Skeet
2009-08-07 11:59:44