In Asp.net, We Can cache some of our static data to improve the website performance. The following is an example of using cache on msdn. Which of the following functions can be very interesting?
You can specify a callback for the cache item. When the cache item is removed, the callback method is called to notify us. An Application of our company uses this method to cache some updates to the database, to avoid frequent operations on the database and improve the performance. When the cache is cleared, the cached data in the callback is called and written to the database. This method causes thread blocking when the concurrency traffic is high. This leads to soaring CPU usage. At last, all threads in the thread pool may be exhausted.
Code < Html >
< Script runat = Server Language = " C # " >
Static Bool Itemremoved = False ;
Static Cacheitemremovedreason reason;
Cacheitemremovedcallback onremove = Null ;
Public void removedcallback (string K, object V, cacheitemremovedreason R) {
itemremoved = true ;
reason = r;
}
Public VoidAdditemtocache (Object sender, eventargs e ){
Itemremoved= False;
Onremove= NewCacheitemremovedcallback (This. Removedcallback );
If (Cache [ " Key1 " ] = Null )
Cache. Add ( " Key1 " , " Value 1 " , Null , Datetime. Now. addseconds ( 60 ), Timespan. Zero, cacheitempriority. High, onremove );
}
Public Void Removeitemfromcache (Object sender, eventargs e ){
If (Cache [ " Key1 " ] ! = Null )
Cache. Remove ( " Key1 " );
}
</ Script >
< Body >
< Form runat = " Server " >
< Input type = Submit onserverclick = " Additemtocache " Value = " Add item to cache " Runat = " Server " />
< Input type = Submit onserverclick = " Removeitemfromcache " Value = " Remove item from Cache " Runat = " Server " />
</ Form >
<% If (Itemremoved ){
Response. Write ( " Removedcallback event raised. " );
Response. Write ( " <Br> " );
Response. Write ( " Reason: <B> " + Reason. tostring () + " </B> " );
}
Else {
Response. Write ( " Value of cache key: <B> " + Server. htmlencode (Cache [ " Key1 " ] As String ) + " </B> " );
}
%>
</ Body >
</ Html >
the reason is that the cache is actually a global object, so access to the cache is synchronized internally through a readerwriterlock. When the callback method is called by removing the cache item, the callback method accesses the database again. As a result, the removal of cache items occupies the lock for a long time, and other requests cannot be read and written to the cache, thus blocking other threads in the thread pool. Therefore, the callback method of the cache item is not suitable for calling long-time operations. It is best to remove the cache item and call subsequent operations on your own. Avoid lock contention.