Broodmdh
February 8th, 2006, 02:28 PM
I have important data that I need fast access to, and it has to be non-volatile. I've read that caching is a better practice for .net than using application variables, but can cached data be dumped when memory levels get low? I want to store arrays; is one method better than the other? Can someone give me a demostration of the syntax for storing and recalling arrays from these objects? Thanks.
mmetzger
February 9th, 2006, 11:37 AM
You can't rely on any of the Application / Session / Context / Cache variables to stay in memory. The best thing to do is have a loader function that tries to load the stored variable (from app, cache, etc.) and checks if it's null. If so, load it from the data source (db, file, etc.) and store it back in the stored variable.
Storing an object in one of these is typically just:
Application["MyArray"] = myArray;
Cache["MyArray"] = myArray;
...etc...
Retrieving requires you to cast the object:
int[] myArray = (int[]) Application["MyArray"];
...etc...
A better way is have a method like:
int[] myArray = null;
try
{
myArray = (int[]) Application["MyArray"];
if (myArray == null)
{
myArray = LoadArray();
Application["MyArray"] = myArray;
}
}
catch (System.Exception ex)
{
... handle exception here - may just reload array...
}
... use myArray...
Note that you can easily substitute cache, session, etc in for Application.