C # cache learning Summary

Source: Internet
Author: User
Tags connectionstrings visual studio 2010

Yesterday I sorted out the basic usage of the cache and the usage of the cachedependency class of the cache dependency class. Today I sorted out the cache database dependency class sqlcachedependency.

1. Database dependencySqlcachedependency

The database cache dependency mainly solves the problem of how to promptly notify the cache and update the data in the cache when the database content changes.

Syntax definition:

The main constructor of the sqlcachedependency class is as follows:

Public sqlcachedependency (string database, string table)

Parameter 1 indicates the database in which the cache is to be enabled, and parameter 2 indicates the cached table. In actual use, you only need to specify the cached database and table.

The method is attribute application (the code is similar to cachedependency). However, SQL needs to configure web. config and set the database cache before using the sqlcachedependency cache class.

Step 1: Configure web. config as follows:

<! -- Database connection statement --> <configuration> <connectionstrings> <Add name = "Config" connectionstring = "Data Source = .; initial catalog = cachedata; persist Security info = true; user id = sa; Password = 123 "providername =" system. data. sqlclient "/> </connectionstrings> <! -- Add --> <! -- Note: The value of Add name in the configuration is the database name, connectionstringname is the same name as the database connection field --> <caching> <sqlcachedependency enabled = "true" polltime = "1000"> <databases> <Add name = "cachedata" connectionstringname =" config "polltime =" 1000 "/> </databases> </sqlcachedependency> </caching>

2. vs cache Configuration:

Open the "Start" | "All Programs" | "Microsoft Visual Studio 2010" | "Visual Studio Tools" | "Visual Studio 2010 naming prompt" menu command.

Enter the aspnet_regsql.exe-s sqlserver server-u <username>-P <password>-ed-D database name-et-T table name in the Command box.

If there is no authentication input: aspnet_regsql.exe-s sqlserver server-ed-D database name-et-T table name

Run the command;

3. Page code;

Private Static sqlcachedependency mydep; protected void page_load (Object sender, eventargs e) {label1.text = datetime. Now. tostring (); If (! Ispostback) {// The cache is the database name, And t_sqlcache is the cache table dataset DS = GetSet (); If (Cache ["sqlcon"] = NULL) {// Add the cache sqlcon, the cache value is the content of the database table. mydep = new sqlcachedependency ("cache", "t_sqlcache"); cache. add ("sqlcon", DS, mydep, datetime. now. addseconds (60), timespan. zero, cacheitempriority. normal, null) ;}} protected void button#click (Object sender, eventargs e) {If (mydep. haschanged) {// reminder when the database value is changed; response. write ("database modification time:" + mydep. utclastmodified);} If (Cache ["sqlcon"] = NULL) {// After the cache expires or the database value is modified, the cache loads mydep = new sqlcachedependency ("ajax ", "t_ajaxld"); dataset DS = GetSet (); cache. add ("sqlcon", DS, mydep, datetime. now. addseconds (60), timespan. zero, cacheitempriority. normal, null);} This. gridview1.datasource = cache ["sqlcon"]; // bind data this. gridview1.databind ();} // <summary> // generate dataset /// </Summary> /// <returns> </returns> private dataset GetSet () {dataset DS = new dataset (); string SQL = "select * From t_sqlcache"; string Config = configurationmanager. connectionstrings ["Config"]. connectionstring; // database connection statement using (sqlconnection CNN = new sqlconnection (config) {using (sqlcommand CMM = new sqlcommand (SQL, CNN )) {sqldataadapter dapter = new sqldataadapter (CMM); dapter. fill (DS) ;}} return Ds ;}

C # the basic content of the cache is similar. Some practical applications will be summarized later. Some differences between sessions and cache will be reproduced in the ground:

Difference between session and Cache

In the past, there were many methods to cache data, including client cookies, Server sessions, and applications. Cookie is a set of data stored on the client, which is mainly used to save personal information such as the user name. Session stores the dialog information. Application is the information stored in the entire application, which is equivalent to a global variable. Sessions are usually used most frequently. What is the difference between sessions and cache?

This section describes the differences between session cache and cache based on your experience.

(1) The biggest difference is that the cache provides a cache dependency to update data, and the session can only determine whether the cache data is valid Based on the defined cache time.

(2) even if the application is terminated, as long as the cache time defined in the cache. Add method does not expire, the cached data will still exist the next time the application is enabled. The session cache only exists in one session. After the session ends, the data becomes invalid.

(3) sessions are easy to lose, leading to data uncertainty, but the cache does not.

(4) because the session is loaded every time, it is not suitable for storing a large amount of information. Otherwise, the server performance will be reduced. The cache is mainly used to store large-capacity information, such as multiple tables in the database.

(5) the beta version of vs2005 provides parameters to save the cache on the hard disk. However, this function is canceled in the official version, and it is estimated that it will be implemented again in later versions. The session can only be stored in the memory, which affects its performance.

To improve the effective usage of the cache, we recommend that you use the cache for infrequently modified data.

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.