. Net Cache and (the difference between Httpruntime.cache and HttpContext.Current.Cache)

Source: Internet
Author: User

Because the program uses the need to cache multiple databases in the context of the current session, all the information is checked.

We're in. NET usage is often used in cache objects.
In addition to the Cache under System.Web.Caching, we can also use HttpContext.Current.Cache and Httpruntime.cache
So what's the difference between HttpContext.Current.Cache and Httpruntime.cache?
As can be seen from the explanation on MSDN, Httpruntime.cache is application-level and HttpContext.Current.Cache is defined for the current web context.
However, in fact, these two are all called the same object, the difference is: httpruntime In addition to the Web can be used outside, non-web programs can also be used.
HttpContext can only be used in the Web.

So, wherever possible, we use httpruntime as much as possible (however, how to invoke between different applications is also a problem).


faster read data, we usually load the commonly used data into the cache in. NET, the existence of the cache can depend on many ways, mainly used in the HttpContext.Current.Cache class here, I mainly write several kinds of dependency way1: Do not rely on any conditions HttpContext.Current.Cache.Insert (stringCacheName,Objectobj) in theory, the cache is permanently saved, but when the server restarts, the memory is lost when it is tight. 2: HttpContext.Current.Cache.Insert (stringKeyObjectvalue, cachedependency dependencies, DateTime absoluteexpiration, TimeSpan slidingexpiration); //cachedependency cache dependencies, absoluteexpiration absolute expiration time, slidingexpiration the last access time interval//We mainly talk about two types of cache dependencies2.1: File dependent, so simple//as soon as the file changes, the cache moves outHttpContext.Current.Cache.Insert (CACHENAME,OJB,NewSystem.Web.Caching.CacheDependency (FilePath)); 2.2: SQL Server database dependent//I'm here, SQL2005 .first look at whether the database notification is available, be sure to turn on the notification Select DATABASEPROPERTYEX ('Database name','isbrokerenabled'); If a value of 1 means that the ALTER DATABASE game176admin is availableSetEnable_broker;//OpenALTER DATABASE Game176adminSetDisable_broker;//CloseIn the Global.asax file, we do something at the beginning and end of the application .voidApplication_Start (Objectsender, EventArgs e) {//code to run when the application startsTry{System.Data.SqlClient.SqlDependency.Start (stringStrcon);//Open}Catch { }} voidApplication_End (Objectsender, EventArgs e) {//code to run when the application shuts downTry{System.Data.SqlClient.SqlDependency.Stop (stringstrcon);}Catch{}} preparation is complete we'll write a method to add a database dependencyvoidAddsqldependency (stringStrcon,stringstrSQL, Onchangeeventhandler sqldep_onchange) {Try{using(SqlConnection conn =NewSqlConnection (Strcon)) {SqlCommand Comm=NewSqlCommand (strSQL, conn); SqlDependency SQLDEP=NewSqlDependency (comm); Sqldep.onchange+=Sqldep_onchange;if(Conn. state = =connectionstate.closed) Conn. Open (); Comm. ExecuteNonQuery ();}}Catch(Exception ex) {Logutility.add (ex);}} //the above method is to tell the database, when you specify the table data changes, to move out of the cachewe can now add the MyObject obj= httpruntime.cache["CacheName"] asMyObject;if(NULL==obj) {Try{obj=getobj (...);}Catch(Exception ex) {Logutility.add (ex); obj=NULL;}if(NULL!=obj) {addsqldependency (Strcon,"Select ID from dbo.tablename;select id1 from Dbo.tablename1",Delegate(Objectsender, Sqlnotificationeventargs e) {//Do somethingHttpRuntime.Cache.Remove ("CacheName");}); HttpRuntime.Cache.Insert ("CacheName", obj);}} The tables used in the SQL statements above, as long as any data in these tables are changed, the database will be notified, then the cache will move, select fields and the cache is not related, only the table name has a relationship, all you want to select the smallest field. Many times, for this field, When designing a table, add a minimum dependency column. Note: Any cache may be lost and must be checked before use, such as: MyObject obj=httpcontext.current.cache ("CacheName") asMyObject;if(NULL==obj) {obj=....... HttpContext.Current.Cache.Insert ("CacheName", obj); Page declaration of}cache Usage<%@ outputcacheduration="#ofseconds" Location="any| Client| downstream| server| None"VaryByControl="controlname"VaryByCustom="browser|customstring"VaryByHeader="Headers"VaryByParam="parametername"%>The cache Usage Code Control HttpCachePolicy class is specifically used for the control cache and can be accessed using RESPONSE.CAHCE to access instances of this class Response.Cache.SetExpires ( DateTime.Now.AddSeceonds (Ten)); Response.Cache.SetCacheability (Httpcacheablility.public); Response.Cache.SetValidUnitlExpires (true); -----------------------above are cached pages, the following is the cache data----------------------------the lifetime of the Cache class is equal to the lifetime of the application three usage1: Save: cache["Key"] =MyData; Take: MyData= cache["Key"];if(MyData! =NULLUse (MyData); This method is stored in the cache's data lifecycle equal to the application lifecycle and does not support cleanup, expiration, dependencies, and other functions. 2: Save: Cache.Insert (stringKey,Objectvalue,cachedependency dependencies,//dependencies, set cache-valid dependencies, such as setting and a file-related, the file changes, it failsDateTime Absoluteexpireation,//set a fixed expiration timeTimeSpan slidingexpiration,//set how long after the last visit expiresCachepriority priority,//Setting the cache is not enough, the cache automatically clears the importance of caching, can you clearCacheItemRemovedCallback onRemoveCallback//set the event that is raised when purging) Example:Cache.Insert ("Mydata", MyData,NewCaching.cachedependency (Server.mappah ("Mydata.xml")));//set effectivity and a file aboutCache.Insert ("Mydata", MyData,NULL, DateTime.Now.AddDays (1), Cache.noslidingexpiratin);//two expiration time set one of them, the other to be set to 0, with Noabsolute (Sliding) Expiration enumerationCache.Insert ("MyData", MyData,NULL, Cache.noabsoluteexpiration,timespan.fromminutes (Ten));//Can't be less than 0 a year.Cache.Insert ("MyData", MyData,NULL, Cache.noabsoluteexpiration,timespan.fromminutes (Ten), Caching.CacheItemPriority.NotRemovable,NULL);//abovenormal| belownormal| Default| high| low| normal| Notremovable Public voidRemovedCallback (stringKeyObjectValue,cacheitemremovedreason reason) {if(Reason = =cacheitemremovedreason.dependencychanged) Response.Write ("The file's changed, go check it out!");} Cache.Insert ("Mydata", MyData,NewCaching.cachedependency (Server.mappah ("Mydata.xml"), DateTime.Now.AddDays (1), Cache.noslidingexpiration,cacheitempriority.high,NewCacheItemRemovedCallback ( This. RemovedCallback)); Clear can be used Cache.remove ("Key"); method3: Cache.Add method, usage and insert almost, the difference is that add encountered the key has been assigned value will fail, insert will not, but replace the original value; add returns the cached data item, insert does not

. Net Cache and (the difference between Httpruntime.cache and HttpContext.Current.Cache)

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.