I have an object that has relatively high initialization cost that provides a thread-safe calculation method needed to process web service requests.
I'm looking for the best way to keep an initialized instance available between requests.
One method is to declare it as a static variable. It would then remain available until the AppDomain is recycled.
This is an older web service that does not use WCF, but converting is an option if that would provide a better solution.
Is there a better approach?
What about caching the object in HttpRuntime.Cache
?
MyObject val = (MyObject)HttpRuntime.Cache["MyCacheKey"];
if (val == null)
{
val = // create your expensive object here
HttpRuntime.Cache.Insert("MyCacheKey", val, null,
DateTime.Now.AddSeconds(3600),
System.Web.Caching.Cache.NoSlidingExpiration);
}
Here I leave it in the cache for up to an hour, but you can vary this as needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With