Introduction to Cache Usage in ASP. NET and asp. netcache
Cache is a high-speed Cache. I think many people have the same first impression on him. I feel that it will certainly improve the system performance and speed. Indeed. The original intention of Net to launch the cache is indeed this. So how does cache improve system performance and speed? Can I use cache to improve performance in all cases? Is it because the more cache is used, the better? I have some experience in recent R & D projects, and I hope to discuss it with you as a summary. If there are any mistakes, I hope you can criticize and correct them.
1. How does Cache work?
Cache is a public memory disk allocated to the server.
The so-called public cache allows all client browsers to access the cache through background code. It targets all users, and session is a memory segment on the server, however, it targets a single user. It is a memory block of the server, that is, each cache occupies server resources once it is created. So from this point, we can say: the more cache, the better.
The cache has a time limit. When the expiration time of the server is exceeded, the cache will be recycled by the server.
C. cache can store all objects
2. How to create and destroy a Cache
Create cache
In. In the. Net environment, use the Cache. Insert (string key, object o) method. The key represents the cache ID, and o represents the object stored in the cache.
Destroy cache.
In the Cache. Remove (string key) method, the key represents the cache ID.
Call cache.
Cache supports packing/unpacking. If you can pass a DataSet object ds to the Cache. insert ("dsCache", ds) is stored in the Cache, and can be accessed by unpacking DataSet ds = (DataSet) Cache ["dsCache.
3. When to use cache?
Cache is generally used when data is relatively fixed and frequently used. For example, you can store product information into the cache in the invoicing system and call the cache when you call product information. This greatly reduces the interaction between users and databases, improves system performance. On the contrary, the cache is not suitable for areas with fast data changes and narrow application scope. For example, you can save a specific purchase order to the cache.
4. cache call considerations
The Cache has a time limit. When the expiration time set by the server is exceeded, it will be recycled by the server. When the cache is recycled, the corresponding memory block will be cleared. When you access the object through the cache ["cachekey"] Again, the return value is null. Therefore, exceptions may occur in the following calls:
DataSet ds = (DataSet) Cache ["cacheds"]; DataRow dr = ds. table [0]. row [0]; // error. ds is null and Table 0 does not exist.
The correct statement should be:
DataSet ds If(Cache[“cacheds”] != null) { ds = (DataSet)Cache[“cacheds”]; } Else { ds= GetDsFromDataBase(); } DataRow dr = ds.Table[0].Row[0];