Each project has some global and common information. If this information is loaded during each usage, it will consume a lot of resources, especially for systems with high access pressure. Therefore, in this case, it is necessary to put the global information in the cache, so that the data can be quickly read, saving a lot of valuable CPU and IO.
Projects usually use application and cache to implement the cache function. Their usage is:
1) application:
Application ["test"] = "this is a application message! ";
2) cache
Cache. Add ("Key1", "Value ");
The two methods are similar. They both use name/value pairs to store data. When reading data, you only need to use a key to obtain the cached value.
Which of the two is more advantageous? The answer is that CACHE is more flexible to use. Features:
1. Self-defined cache update mechanism
Some projects need to regularly obtain the latest data, such as the weather forecast, which may be read once every 10 minutes. This can be achieved by using the CACHE method.
// Monitor a time
Public void CreateDependency (Object sender, EventArgs e ){
// Create a DateTime object.
DateTime dt = DateTime. Now. AddSeconds (10 );
// Create a cache entry.
Cache ["key1"] = "Value 1 ";
CacheDependency dependency = new CacheDependency (null, dt );
Cache. Insert ("key2", "Value 2", dependency );
DisplayValues ();
}
2. When the cached source is modified, the cache can be updated again. The cache source can be a variable, a file, or a directory.
// Monitor a variable
Public void CreateDependency (Object sender, EventArgs e ){
// Create a DateTime object.
// DateTime dt = DateTime. Now. AddSeconds (10 );
// Create a cache entry.
Cache ["key1"] = "Value 1 ";
// Make key2 dependent on key1.
String [] dependencyKey = new String [1];
DependencyKey [0] = "key1 ";
CacheDependency dependency = new CacheDependency (null, dependencyKey, null );
Cache. Insert ("key2", "Value 2", dependency );
DisplayValues ();
}
3. the cache is automatically updated with multiple combinations, such as monitoring a file at the same time and automatically updating at a specified interval.
// Monitor a time and variable
Public void CreateDependency (Object sender, EventArgs e ){
// Create a DateTime object.
DateTime dt = DateTime. Now. AddSeconds (10 );
// Create a cache entry.
Cache ["key1"] = "Value 1 ";
// Make key2 dependent on key1.
String [] dependencyKey = new String [1];
DependencyKey [0] = "key1 ";
CacheDependency dependency = new CacheDependency (null, dependencyKey, dt );
Cache. Insert ("key2", "Value 2", dependency );
DisplayValues ();
}
Compared with the APPLICATION, the CACHE is more flexible.