Several methods of ASP.NET cache management

  • 2020-05-19 04:30:19
  • OfStack

Although cache management is no longer an issue in Windows applications, it is still a challenge in the web environment. Because HTTP is a stateless protocol and the web service is unable to identify users with different requests. It is important for us to identify which particular user made the different requests and to store this information so that it can be reused in future requests. ASP.NET provides a number of features for storing this data on both the client and server side, but sometimes we get confused about "when do we use them (and which)?" In ASP.NET, we encounter objects like Session, Application, and Cache, and in order to use them effectively in web applications, it is important for us to understand the differences between them.

background

In this article, I'll talk about different approaches to cache management in ASP.NET. In web applications, it is sometimes necessary to store data on the server side to avoid the overhead of retrieving data from the database and data formatting logic to improve performance, and we can reuse the same data across users, applications, and machines in subsequent requests. So, in order to do that we need to cache the data on the server side.

Caching has helped us improve quality of service in three ways

The & # 8226; Performance (Performance) - caching improves application performance by reducing the overhead of retrieving data and formatting operations.
The & # 8226; Scalability (Scalability) - because caching reduces the overhead of retrieving data and formatting operations, it reduces the load on the server side, thus increasing application scalability.
The & # 8226; Availability (Availability) - because the application reads data from the cache, the application can continue to run if another system or database connection fails.
Different methods for

In the web application, we can cache data, pages, and so on on the server side and the client side. Let's look at one on the server side and one on the client side.

Server side cache management

ASP.NET Session state

Session is used to cache the information of each user. This means that the data cannot be Shared across users, and it is limited to the user who created the session (Session) to use it. In ASP.NET, Session is used to distinguish users.

Session can be hosted in three ways:

The & # 8226; In-process (Inproc) - session state is stored in the aspnet_wp.exe process. Session data is lost when the application domain is recovered.
The & # 8226; Status server (StateServer) - session state is stored in different processes and can be on different machines. Because it can be stored on different machines, this option supports web groups.
The & # 8226; Sql database (SQLServer) - session state is stored in the SqlServer database, and this option also supports website groups.
For the state server and the Sql database, both need to serialize the cached objects because the data to be cached is cached outside of the application process. Both of these approaches affect performance because data retrieval and storage take more time than in-process caching. So decide which caching method to use based on your specific needs.

The following sample code shows how to use Session


string empNum = Request.QueryString["empnum"];
if (empNum != null)
{
    string details = null;
    if (Session["EMP_DETAILS"] == null)
    {
        //Get Employee Details for employee number passed
        details = GetEmployeeDetails(Convert.ToInt32(empNum));
        Session["EMP_DETAILS"] = details;
    }
    else
    {
        details = Session["EMP_DETAILS"];
    }
    //send it to the browser
    Response.Write(details);
}

ASP.NET application object

ASP.NET provides an object called Application to store data that all users can access. The life cycle of this object is the same as the life cycle of the application, which is recreated when the application is started. Unlike the Session object, the Application object can be requested by all users because this object is created and managed in the application domain and is therefore not available in the Web web group. Application objects are ideal for storing application metadata (Config file data), which can be loaded into Application objects and accessed by each user request throughout the application cycle without reloading. However, if there is a requirement that the cache data be invalidated whenever changes are made to the Config file during the application run, then the Application approach does not provide such support. In this case, cache objects are considered, and the use of cache objects is described below.

ASP.NET cache object

ASP.NET cache object is my favorite caching mechanism, which is why I'm going to say a little more here. ASP.NET provides a key-value pair (key-value pair) object --cache object, which can be obtained in the system.web.caching namespace. Its scope is application domain, lifecycle, and application lifecycle 1. Unlike the Session object, it can be accessed by different users.

Although Application and Cache objects are very similar, the main difference is that Cache objects have more features, such as expiration policies, cache dependencies. It means that the data store is either out of date or clear when the cache object can change based on a predefined time or the entities it depends on, and this feature is not supported by the Application object.

Let's discuss the expiration policies and cache dependencies it supports.

Rely on

Dependency means that the cached object is cleared when the dependent entity changes. So you can define a dependency that clears the cache object when the dependent object changes. ASP.NET supports two types of dependent objects.

The & # 8226; File dependency (File Dependency) - it provides a mechanism to automatically clear cache objects whenever a disk file changes. For example, my application USES XML to store error information (a mapping of error Numbers and error messages) and to retrieve error messages with error Numbers. Every time I want to read an error message, instead of reading it from disk every time, I put it into the Cache cache when the application starts up so that it can be retrieved later. What happens when I add a new error message or modify an existing error message while the program is running? Do I need to stop the program to change this information? Not at all. When you do this, the data in the Cache cache is automatically invalidated. This is known as the file cache dependency.
The following example shows how file caching can be used to invalidate the Cache cache. So, whenever you make a change to the error.xml file, the cache entry is automatically invalidated.


object errorData;
 //Load errorData from errors.xml 
 CacheDependency fileDependency = 
     new CacheDependency(Server.MapPath("errors.xml")); 
 Cache.Insert("ERROR_INFO", errorData, fileDependency);

The & # 8226; Key dependencies (Key Dependency) - key dependencies are very similar to file dependencies, except that 1 does not depend on files but on other entries. When an Cache dependent entry changes or is deleted, the cache will automatically expire. This method is useful for adding interdependent objects to the cache, and is useful when the host object is changed and these interdependent cache objects are released. For example, if the employee number, name, and salary are added to the cache at the same time, all employee information in the cache will be erased if the employee number is changed or deleted. In this example, the employee number ACTS as a dependency on the employee information.
The following example shows how key dependencies can be used to invalidate a cache.


string[] relatedKeys = new string[1]; 
relatedKeys[0] = "EMP_NUM";
CacheDependency keyDependency = new CacheDependency(null, relatedKeys); 
Cache["EMP_NUM"] = 5435;
Cache.Insert("EMP_NAME", "Shubhabrata", keyDependency);
Cache.Insert("EMP_ADDR", "Bhubaneswar", keyDependency);
Cache.Insert("EMP_SAL", "5555USD", keyDependency);

Expiration policy (Expiration Policy)

The expiration policy defines how and when to let cached objects expire.

The & # 8226; Time-based expiration (Time based expiration) - time-based expiration provides a way for users to pre-define the expiration time for cached objects. This pre-defined time can be either an absolute time such as 12 o 'clock on October 31, 2005, or a relative time, relative to the cache object's storage time.


//Absolute Expiration
Cache.Insert("EMP_NAME", "Shubhabrata", null, 
             DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);
//Sliding Expiration
Cache.Insert("EMP_NAME", "Shubhabrata", null, 
             Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(60));

How do you know if a cache object has been cleared?

The example above describes how to clear a cache object, but sometimes we need to know when an object is cleared from the cache. Yes, we can do this by using callbacks. In the above error message example, the cached object is cleared whenever error.xml changes. Suppose we want to update the cache with the latest error messages. When an object is cleared from the cache, we can use a callback (Callback) to do the next step (reload the object into the cache).

The following example shows a scenario in which callbacks are used when a cache expires.


private void AddItemsToCache()
{    
    int empNum = 5435;
    CacheItemRemovedCallback onEmpDetailsRemove = 
                    new CacheItemRemovedCallback(EmpDetailsRemoved);
    Cache.Insert("EMP_NUM", empNum, null, 
                              Cache.NoAbsoluteExpiration, 
                              Cache.NoSlidingExpiration, 
                              CacheItemPriority.Default, 
                              onEmpDetailsRemove);
}
private void EmpDetailsRemoved(string key, object val, 
                              CacheItemRemovedReason reason)
{
    //When the item is expired
    if (reason == CacheItemRemovedReason.Expired)
    {
        //Again add it to the Cache
        AddItemsToCache();<BR>    }
}

In the above example, you must pay attention to the CacheItemPriority parameter, which is used in conjunction with the Callback parameter 1. CacheItemPriority is used to set the priority of objects added to the cache. This priority tells Cache that when memory 1 is very low, this priority indicates the order in which the objects are released. This process is called cleanup (scavenging).

.NET Remoting

So you might be thinking, how is NET remoting used for data caching? When I first heard the question, it came to my mind. As you know, NET Remoting shares objects with clients through singletons, so objects using singletons can be used to cache data to share data with different clients. Because NET Remoting can run outside of processes and machines, this feature is useful when we want to cache objects across services, across users, and especially in groups of websites. This way we can cache the data into the data members of the singleton object and provide methods to read and store the data. When we implement this method, we must ensure that the cached remoting objects are not cleared by the garbage collector. So we have to set the cache of the Remoting object to never expire and never timeout. We can override the InitializeLifetimeService and MarshalByRefObject methods to return Null. But the main problem with doing this is performance, which is worse than other methods for analysis. However, it is up to the designer or developer to choose the most appropriate method according to the specific requirements.

Memory mapped file (Memory-Mapping files)

Everyone knows what a memory-mapped file is, and it is based on a specific address range of files mapped to the physical disk to the application's storage space. This approach allows different processes to use the same data to increase application performance. Because the use of memory-mapped files is not popular in the ASP.NET application, I personally do not recommend this method because it adds complexity to the application, and NET Framework does not support it. But if someone likes to use this approach, they must develop customized solutions for their needs.

Static variables (Static variables)

We can use static variables to store global data or objects that can be accessed throughout the application lifecycle. Similarly, we can use static objects to cache data, and we can provide methods to retrieve and store data from the cache. Because static objects are stored in a process, performance is very fast. But implementing expiration policies and cache dependencies with static variables is very complex, and I prefer Cache to static variables. Another problem is that user-defined cache objects must be thread-safe, so you have to be careful how you implement them.

A custom static cache can be implemented by:


public class CustomCache
{
    //Synchronized to implement thread-safe
    static Hashtable _myCache = 
             Hashtable.Synchronized(new Hashtable());

    public static object GetData(object key)
    {
        return _myCache[key];
    }

    public static void SetData(object key, object val)
    {
        _myCache[key] = val;
    }
}

The database

We can use the database to store data to achieve cross-user, cross-machine data sharing. This is a great way to cache very large data objects. Using this approach to store small amounts of data is not cost-effective (low performance), and storing small amounts of data can be used to find caching mechanisms within other processes. Cached data stored in the database needs to be serialized into XML for easy storage and retrieval, and we can use other types of serialization formats in.NET Framework as well.

Page output cache (ASP.NET page output caching)

Sometimes, our web application does not change for certain pages within a certain time frame. For example, on the HR site, the employee salary information does not change frequently, but only once a month. 1. Generally speaking, changes occur on the first day of a month. Therefore, for a particular employee, the content of that employee's page will not change for a month. So it's a good idea to cache these pages on the server to avoid the process of recalculating each request. To do this,.NET gives us the ability to cache the output page at a specific time on the server. It also provides the feature of caching page fragments. I won't go into the details of this caching method here, because there is a lot of detail on the web about this. This is a very long section and if we talk about it now, I plan to talk about it in other sections.


<!-- VaryByParm - different versions of same page will be 
cached based on the parameter sent through HTTP Get/Post
Location - where the page is cached -->
<%@OutputCache Duration="60" VaryByParam="empNum" 
                                       Location="Server"%>

Let's compare these caches that we're talking about with 1:

methods Are web groups supported? note

ASP.NET Session State
- InProc
- StateSerer
- SQLServer


No
Yes
Yes

Unlike other option, it stores only user session specific data ASP.NET Application Object No ASP.NET Cache Object No .NET Remoting Yes Memory-Mapped files No Static Variables No Database Yes ASP.NET Page Output Caching No

Client side cache management

In the previous section we discussed non-caching on the server side, but sometimes we want to cache data and pages on the client side to improve performance. Using client-side caching can reduce the load on the server, but this caching mechanism has security issues because the data is stored on the client side. There are also different ways to cache on the client side, and I'll briefly cover several.

Cookies

Cookie is a familiar concept among web developers. Cookie is stored on the client side and sent to the server each time the client sends a request, and then sent back to the client when the server responds. Because it limits the number of bytes (4,096 bytes), it can only cache smaller data. It can use an expiration policy to invalidate it after a specified period of time. The following example shows how to use Cookie in ASP.NET.


if (this.Request.Cookies["MY_NAME"] == null) 
{ 
    this.Response.Cookies.Add(new HttpCookie("MY_NAME", 
                                       "Shubhabrata Mohanty")); 
} 
else 
{ 
    this.Response.Write(this.Request.Cookies["MY_NAME"].Value); 
}

ViewState

.NET ViewState is a new concept. The data and controls associated with the page are stored in ViewState, and these reserved values can span multiple request servers. If you remember, in VB-ASP application development, data is stored across multiple requests through the Hidden control. ViewState is actually an internal implementation of the hidden control in ASP.NET, but it is hashed to increase security compared to the hidden control. To see how ViewState is implemented, you can open the page to see the source code. ViewState also cannot store large amounts of data because it sends every request to the server.


protected void Page_Load(object sender, EventArgs e) 
{
    if (this.ViewState["MY_NAME"] == null) 
    { 
        this.ViewState["MY_NAME"] = "Shubhabrata Mohanty";
    } 

    //txtName is a TextBox control 
    this.txtName.Text = this.ViewState["MY_NAME"].ToString(); 
}

Hidden fields

Hidden field is very popular in VB-ASP Web development. The use of Hidden fields is very similar to other controls, but it is not visible on the output page. Like ViewState1 it also can't store large amounts of data. Note: the hidden framework (Hidden frames) can cache data on the client side, but not all browsers support the hidden framework.


<!--In ASP.NET-->
<asp:HiddenField ID="myHiddenField" Value="Shubhabrata" 
                                             runat="server" />
<!--In HTML-->
<input id="myHiddenField" type="hidden" value="Shubhabrata" />

Microsoft IE browser cache

Since we're talking about Microsoft's ASP. NET, why not talk about another one of Microsoft's caching capabilities? Microsoft's IE browser provides another mechanism to cache pages on the client side, which can be added to the HTML page using the EXPIRES Settings directive or manually set in IIS. Go to the HTTP label properties window in IIS and select the make content expire check box. We can use this setting to cache static web pages and images on the client side.


Related articles: