Reputation: 2206
I need to cache a very small amount of data for a maximum of one hour for an ASP.NET web application (one instance). Obviously this needs to be thread-safe so I can access the cache from within my requests.
I want to do this "in process", and not use anything external.
What would be the easiest way to implement this?
Upvotes: 0
Views: 111
Reputation: 2538
Use static variables. You could write a static cache class including your update logic (maximum of one hour) and store the retrieved data in a static member.
The class will persist in the app pool until it is recycled. This could be too often or too rarely for your use cases. But the caching ability should be fair enough.
For the thread-safety issues you could provide getter methods in this class and make use of the lock
statement.
Upvotes: 1
Reputation: 3955
You can user the Cache object ASP.NET provides you with.
You can create a property that returns the cached object if exist else retrieve it from db.
private myClass myProp {
get{
if (Cache["Key1"] == null)
Cache.Add("Key1", "Value 1", null, DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration, CacheItemPriority.High);
return (myClass)Cache["Key1"];
}
}
Upvotes: 1