Reputation: 7684
In my application, I read some xml files into a list of objects (List<Thing>
) but I want to avoid having to hit the file system on each request. The data in the xml files rarely changes, so I'd like to cache it in some way. Either loading the data on application start or loading it lazy, is fine with me. I will need to be able to use the data throughout my app and run Linq queries against it, almost using it as a mini database in memory. I'll need to be able to change/update the data without it impacting the cached version, so copying the data to a local variable may be needed as well. How can I achieve this?
Upvotes: 2
Views: 6605
Reputation: 15893
One of the main benefits of System.Runtime.Caching.MemoryCache
or System.Web.Caching.Cache
is the capability to set expiration policy on items you cache. If you are going to load data only once and keep it in memory for the life-time of the process, you may as well use a static class member which you create and fill with data in the static constructor of the same class. If your change/update operations should not affect data in memory, you need to load (or copy) the data into another instance of container and change (and possibly save) it.
Upvotes: 1
Reputation: 1065
you can use the cache object for it.
myxmllist = HttpContext.Current.Cache["myxmllist"];
if (myxmllist == null)
{
//get xml from server
HttpContext.Current.Cache.Insert("myxmllist", myxmllist); // add it to cache
}
Upvotes: 2