Analysis of the implementation principle of Session in ASP.net [2] state Manager

Source: Internet
Author: User
Tags abstract bool config session id resource sessions server memory
Asp.net|session state management would have been a very good thing, hehe, but always some manufacturers in the implementation of the time considered less comprehensive. For example, MS in the ASP state management implementation is worse, because only the implementation of a process of memory-based state management, there are many problems:

1. All session data is stored in the process of the WEB service, causing the number of server support sessions to be limited by server memory resources, and also because of the large number of inactive sessions that cause memory to be consumed.
2. Server process crashes can cause all session data to be lost.
3. Sessions cannot be used across processes or under load balancing, unless the load-balancing technique guarantees that the same user can be routed to the same machine each time. Even this will not guarantee the loss of session data due to server crashes.
4. Need cookie support, and now because of security issues, many people in the browser to turn off cookies and JS support.

For this reason, users of the ASP have to manually synchronize session information to an external database with the session ID as the primary key to mitigate similar problems.

In asp.net, these limitations can be avoided because of design considerations:

1. Support for Out-of-process state Management, managing session state through independent State management services or SQL Server state servers
2. Support state maintenance without cookies and avoid cookies by automatically increasing the session ID in the URL
3. Synchronous use of session information through independent State management services or SQL Server state server support for load balancing

The implementation of these features is precisely the four different state managers selected in the Sessionstatemodule.initmodulefromconfig function mentioned in the previous section, based on the mode attribute of the sessionstate tag.


The following are program code:

<system.web>
<sessionstate mode= "InProc"
Stateconnectionstring= "tcpip=127.0.0.1:42424"
statenetworktimeout= "10"
sqlconnectionstring= "Data source=127.0.0.1;integrated Security=sspi"
Cookieless= "false"
Timeout= "/>"
</system.web>



Off mode prevents session management, while ASP.net also allows session support status to be managed by fine-grained management of pages in the page with EnableSessionState attributes
The following are program code:

<%@ Page enablesessionstate= "true| false| ReadOnly "%>



The INPROC mode is compatible with the previous ASP's strategy and realizes the memory-based session state management in asp.net same process space, which is the fastest but the same limit as ASP;
The stateserver mode asp.net the asp.net state Service (Aspnet_state.exe), which is installed independently, to stateconnectionstring the specified IP and port response session status service;
SQL Server mode is a temporary table of memory (with InstallSqlState.sql, using the tempdb, by sqlconnectionstring the server specified) Memory database) or stand-alone tables (InstallPersistSqlState.sql monitoring, using a separate ASPState library) to maintain session state.

These four different state managers, in performance, according to the performance tuning and optimizing ASP.net appliation, the relative values are as follows:

The following are references:

Table 4-1: Normalized TTLB (time to last Byte) by session state Mode (in milliseconds per Requests)

CONCURRENT BROWSERS mode = off mode = INPROC Mode = stateserver mode = SQL Server
1 7.81 4.54 8.27 8.47
5 28.28 20.25 27.25 29.29
10 89.38 46.08 77.29 85.11


Table 4-2: Average Requests/Second by Sessions State Mode

CONCURRENT BROWSERS mode = off mode = INPROC Mode = stateserver mode = SQL Server

1 18.86 24.17 18.31 18.11
5 21.66 25.74 21.54 21.34
10 17.23 23.8 18.11 17.6




As you can see, the performance of the Out-of-process state manager is acceptable, whether from TTLB or average requests per second, and of course it needs to be optimized for state management when writing code. However, to use the Out-of-process state manager, objects saved in the session are subject to the restrictions that must be enhanced by binary serialization support.

From a usage standpoint, the state manager is actually managed by the Httpsessionmodule mentioned in the previous section, and accessed through the HttpSessionState interface, as shown in the following diagram:


The underpinnings of the session state implementation in ASP.net on MSDN explains in great detail the principles and uses of several different state managers.

From the implementation point of view, the Sessionstatemodule.initmodulefromconfig function mentioned in the previous section, based on the pattern of the state manager in the configuration file, establishes System.Web.SessionState.InProcStateClientManager, System.Web.SessionState.OutOfProcStateClientManager and System.Web.SessionState.SqlStateClientManager an instance of a three-class state manager. They both inherit from the System.Web.SessionState.StateClientManager abstract base class and pass the System.Web.SessionState.IStateClientManager interface to the HttpApplication improve state management services.

The Istateclientmanager interface is the unified management interface of the state manager, which mainly provides the following functions:
The following are program code:

Internal interface System.Web.SessionState.IStateClientManager.IStateClientManager
{
Configuration Management state Manager
void Configinit (Sessionstatesectionhandler.config Config, Sessiononendtarget onendtarget);
Save SessionStateModule instance for later use
void Setstatemodule (SessionStateModule module);
void Resettimeout (string id);
void Dispose ();

void Set (String ID, sessionstateitem item, bool instorage);

Maintaining state manager content
IAsyncResult beginget (String ID, AsyncCallback cb, Object state);
Sessionstateitem endget (IAsyncResult ar);

IAsyncResult begingetexclusive (String ID, AsyncCallback cb, Object state);
Sessionstateitem endgetexclusive (IAsyncResult ar);
void releaseexclusive (string id, int lockcookie);
}



The Configinit method primarily notifies the state manager when it initializes its work based on configuration and binds the Sessiononendtarget object instance that is responsible for session state cleanup to the conversation manager, which we discuss later in this discussion of the State management implementation. For Outofprocstateclientmanager and Sqlstateclientmanager, the connection to the external server is also initialized at this stage, and through a System.Web.Util.ResourcePool instance, Provide a resource pool based on time policy to maintain the connection;
The Resettimeout method resets the timeout for the specified session; For Inprocstateclientmanager, the timeout is through System.Web.Caching.CacheInternal The cache object that the type implements to use; Outofprocstateclientmanager directly through the MakeRequest function construction request to external independent State manager execution; Sqlstateclientmanager calls the stored procedure tempresettimeout updates the ASPStateTempSessions table's Expiration Expires field;
Dispose method is the resource of State manager, implement to code is to Outofprocstateclientmanager and Sqlstateclientmanager resource pool release;

The Set method stores the specified Sessionstateitem in the session data associated with the ID, and determines whether to release the lock on the session in the event of an exception, based on the state of the object specified by Instorage. Similar to the Resettimeout implementation, Outofprocstateclientmanager sends a request to an external independent state manager; Sqlstateclientmanager calls the stored procedure TEMPUPDATESTATEITEMXXX Update the Expiration Time Expires field, lock State Lock field, and status information in the Session state table ASPStateTempSessions sessionitemshort/ Sessionitemlong (save 7000 bytes of data below or above each). If an exception occurs and the Instorage tag is set, the Tempreleasestateitemexclusive release session lock is invoked first.

The acquisition of data in the state manager is more complex, the Istateclientmanager interface uses the pattern of asynchronous invocations, and the exclusive acquisition data is taken out separately for efficiency gains. The state Manager implementation class asynchronously implements data acquisition operations through several tool methods implemented by the common base class System.Web.SessionState.StateClientManager. Finally, the implementation class completes the operation through the Get and getexclusive methods. The method of obtaining the data inprocstateclientmanager through the cache; Outofprocstateclientmanager through the request; Sqlstateclientmanager through tempgetstateitemxxx Stored procedure complete.

After understanding the implementation and usage of the SessionStateModule control state server, let's take a look at how the upper HttpSessionState is used.



The asp.net session Management internals of Mandeep S Bhatia introduces the principle of complete state information management within HttpSessionState. The HttpSessionState Item property is actually implemented through a sessiondictionary instance.
The following are program code:

public sealed class HttpSessionState: ...
{
Private Sessiondictionary _dict;

public object This[string Name]
{
Get
{
return _dict[name];
}
Set
{
_dict[name] = value;
}
}
}



The construction of this sessiondictionary instance and the HttpSessionState instance is done in the Sessionstatemodule.completeacquirestate method that completes the session construct mentioned earlier:
The following are program code:

public sealed class Sessionstatemodule:ihttpmodule
{
private string _rqid;
Private Sessiondictionary _rqdict;
Private Httpstaticobjectscollection _rqstaticobjects; Static objects, through the page <object runat= "Server" scope= "session"/> Tag settings
private int _rqtimeout;
private bool _rqisnewsession;
private bool _rqreadonly;
Private HttpContext _rqcontext;
Private Sessionstateitem _rqitem;

private void Completeacquirestate ()
{
if (_rqitem!= null)
{
if (_rqitem.dict!= null)
{
_rqdict = _rqitem.dict;
}
Else
{
_rqdict = new Sessiondictionary ();
}
_rqstaticobjects = ((_rqitem.staticobjects!= null)? _rqitem.staticobjects:
_rqcontext.application.sessionstaticobjects.clone ());
_rqtimeout = _rqitem.timeout;
_rqisnewsession = false;
_rqinstorage = true;
_rqstreamlength = _rqitem.streamlength;
}
Else
{
_rqdict = new Sessiondictionary ();
_rqstaticobjects = _rqcontext.application.sessionstaticobjects.clone ();
_rqtimeout = Sessionstatemodule.s_config._timeout;
_rqisnewsession = true;
_rqinstorage = false;
}
_rqdict.dirty = false;

_rqsessionstate = new HttpSessionState (_rqid, _rqdict, _rqstaticobjects, _rqtimeout, _rqisnewsession,
Sessionstatemodule.s_config._iscookieless, Sessionstatemodule.s_config._mode, _rqreadonly);

_rqcontext.items.add ("Aspsession", _rqsessionstate);

}
}



A few of the fields involved here can basically correspond to the public properties provided by HttpSessionState. It should be noted that httpsessionstate.staticobjects is statically defined by the <object runat= "Server" scope= "session"/> on the asp.net page; Rqreadonly is set by the <%@ Page enablesessionstate= "ReadOnly"%> tag mentioned earlier.

At this point, the status manager of the use and implementation of the basic analysis is completed, the following to organize the use of the process:

1. Construction: HttpApplication The HTTP module that implements the IHttpModule interface that is registered in the Initmodules initialization configuration file Machine.config in the initialization process; is constructed and initialized for one of the modules, and its Initmodulefromconfig method constructs and initializes the corresponding state manager according to the configuration of the state manager in the configuration file, and calls the Completeacquirestate method to complete according to various conditions The construction work of HttpSessionState.
2. Use: HttpSessionState through sessiondictionary to implement the state data management of its Item property; Sessiondictionary itself by sessionstatemodule.onreleasestate Write back to the status manager at the appropriate time, and other maintenance operations are done through the SessionStateModule call to the Istateclientmanager interface of the state manager.
3. Implementation: The state manager obtains the encapsulation of the asynchronous invocation from the abstract base class Stateclientmanager, and provides the interface to the SessionStateModule to manage its initialization, release, and management through the Istateclientmanager interface.

Although ASP.net has done a lot of work, personal feelings are far from enough. For example, Inproc/outofproc is actually in memory, only solves a problem of reliability and data centralization synchronization, while SQL Server can solve the problem of capacity, reliability and data centralization synchronization, but the efficiency is affected. In this regard. NET should learn from Java, for example, the Java EHCache and Oscache provide a smooth configurable level two (memory/hard disk) cache media switching, and the latter also provides a simple load balancing support, in addition to the implementation of JBoss, such as ip-based multicast, etc. Implementation of the load-balanced cache implementation of technology, and so on, are far beyond the asp.net provided by the caching mechanism to consider the scope. Although ASP.net also has an independent caching mechanism, MS also proposed cache Application Block reference to achieve, but still a long way to go ah, hehe




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.