State management

1. Application State

In asp.net platform, application state is the place to store data is common to all components in the application and is shared between all requests. The application state can improve the performance of an application, since it normally store data or objects that you need frequently and resource-expensive to create for every request. However, it is also easy to create the opposite effect and slow down the system.

1.1 user applicaiton state

Application state is implemented by the HttpApplicationState class, that is defined in System.Web namespaces. And it is available through HttpContext.Application property.

members description
Add(key,value) add a value to application with the specified key
AllKeys return the collection keys as a string array
Clear() remove application state data
Count   return the number of state data items
Lock() acquires exclusive access to the application state data
Item[index] returns the item with specified index
Item[key] retruns the item with specified key
Remove(key) remove the value with specified key
Remove(index) remove the value with specified index
unLock() release exclusive access to the application state data

Let‘s look at one example of using application state.

        public static object Get(HttpApplicationState appState, AppStateKeys key, object defaultValue = null)
        {
            var keyString = Enum.GetName(typeof (AppStateKeys), key);

            if (appState[keyString] == null && defaultValue != null)
            {
                appState[keyString] = defaultValue;
            }

            return appState[keyString];
        }

        public static void Set(HttpApplicationState appState, AppStateKeys key, object value)
        {
            appState[Enum.GetName(typeof (AppStateKeys), key)] = value;
        }

I wrapped the logic of handling application state into one utility class, which is easy for unit testing and improves the code reusability.

1.2 Understanding the synchronization effect

Asp.net processes requests concurrently, and to ensure that one request is trying to read data that another is trying to modify at the same time, the methods and properties of the HttpApplicationState class are synchronized.

All of the requests can read the data without delay. However, it needs to wait while trying to modify the data, to ensure the current operations have completed.

The performance of synchronization on performance depends on the number of concurrent requests that the application processes, the ratio of read to modification. When you dealing with real project, you will have to decide whether the conventience of being able to share data through HttpApplicationState is worth the performance penalty.

1.3 Performing related operations

The caution must be taken while you are working multiple related values,

The lock method defined in HttpApplicationState provides the exclusive access to the state data collection until the Unlock is called.   

        public static void SetMultiple(HttpApplicationState appState, IDictionary<AppStateKeys, object> data)
        {
            appState.Lock();

            foreach (var key in data.Keys)
            {
                var keyString = Enum.GetName(typeof (AppStateKeys), key);
                appState[keyString] = data[key];
            }

            appState.UnLock();
        }

2. Sessionn State

Even http is a stateless protocol, it is sometimes necessary to identify related request in order to delivery continuity in web applications. Asp.net platform support session and session state, which allows requests from the same browser to be identified.

2.1 Working with session data

Session state is accessed through HttpContext.Session property, which returns System.Web.SessionState.HttpSessionState class.

HttpSessionState members:

Count Returns the number of session state data items
IsReadOnly Return true if the session state data cannot be modified.
IsSynchronized Returns true if the session state data is synchronized
Item[Index]   Fetch state data at the specified index
Item[key] Fetch state data at the specified key
Clear() Remove all state data item
Remove(key) Remove state data at the specified key
Remove(index) Remove state data at the specified index

 2.2 how session works

The entry point of the session feature is a module called SessionStateModule, which handles the AcquireRequestState request life-cycle event and is responsible for associating state data with request.

It looks for a session identifier in each request. The identifier is usually a cookie, and it is used to load the state data into HttpSessionState object which is attached to the HttpContext object associated with the request.

Abandon() Terminates the current session
CookieMode it describes how sessions are identified
IsCookieless returns true if identification is performed without cookies
IsNewSession returns true if the session has been created during the current request
Mode   describe how session state data is stored
SessionID return the identifier of the current session
Timeout the default is 20

The life of a session starts when a request arrives that doesn‘t contain a session cookie. At that time, HttpSessinoState.IsNewSession is true, and a new session identifier is created and assigned to the HttpSessionState.SessionID.

Asp.net platform will not add cookie to the response, if there is no session data.

2.3 Synchronization effect

ASP.NET processes multiple requests concurrently, and modern browser can make multiple requests concurrently.

So, there is a rick of data corruption.

To avoid the risk, asp.net froces request that come from the same session to execute sequentically. However, it slows down the processing of request, even when the request will not modify the session data at all.

2.4 controlling session state

The solution to the problem is to apply SessionState attribute.

[SessionState(SessionStateBehavior.Disabled)]

Default  
Disabled SessionState is disabled for the controller, the requests will be processed concurrently. Attempting to access state will result in an exception
ReadOnly The controller will be able to read session state data, but not modify. 
Required It will cause request to execute sequentially. 

2.5 Configure session and session state

The session feature is configured through sessionState section in the web.config file.

ASP.net platform identified sessions with a cookie, relying on the browser to include it in the request sending to the server. In case cookies is disabled, asp.net provides us with other means of passing session id, such as url.

(Session.CookieMode) - AutoDetect, UseCookie, UseDeviceProfile, UseUri

<System.Web>

  <sessionState cookieless="UseUri" />

</System.Web>

2.6 Storing session data

By default, session state data is stored in memory within processes. But, asp.net does have two other storage options.

InProc This is default value, and store session data in process
off Disables sessions for the entire application
SQLServer The state data will be stored in database. 
StateServer The state data will be stored in a dedicated server process. 
Custom  

2.7 state server

The asp.net platform comes with a separate server that can be used to store session state. The advantage is that you can host the session on a dedicate machine, and it won‘t lost when the application is stopped.

Be remember, the session data is still stored in memory, just the memory of another process, can can run on another server. The state server is only userful if you have a lot of state data.

The state server is a windows service that is installed as part of .net framework.

<sessionState cookieless="UseCookie" mode="StateServer" />

2.8 user sql database

Using a database to store session data ensures taht data isn‘t lost when a process is restarted.

时间: 2024-10-13 23:34:16

State management的相关文章

LINK - Azure - Session/Cache State Management

How to choose which Cache provider to use? https://msdn.microsoft.com/en-us/library/azure/dn766201.aspx use Redis Cache for Session state https://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-session-state-caching/ 版权声明:本文为博主原创文章,

Web前端的状态管理(State Management)

http://blog.csdn.net/hj7jay/article/details/54340672

PatentTips - Virtual machine management using processor state information

BACKGROUND OF THE INVENTION The invention generally relates to virtual machine management, and more particularly to efficient scheduling of virtual machines using processor state information. Virtualization of machine resources has been of significan

[Hapi.js] Managing State with Cookies

hapi has built-in support for parsing cookies from a request headers, and writing cookies to a response, making state management easy and straight-forward. It even has built in support for cookie encryption and auto detects when a cookie contains JSO

原生 JavaScript 实现 state 状态管理系统

原生 JavaScript 实现 state 状态管理系统 Build a state management system with vanilla JavaScript | CSS-Tricks 在软件工程中,状态管理已经不是什么新鲜概念,但是在 JavaScript 语言中比较流行的框架都在使用相关概念.传统意义上,我们会保持 DOM 本身的状态甚至声明该状态为全局变量.不过现在,我们有很多状态管理的宠儿供我们选择.比如 Redux,MobX 以及 Vuex,使得跨组件的状态管理更为方便.这

JAVA面试中问及HIBERNATE与 MYBATIS的对比,在这里做一下总结(转)

hibernate以及mybatis都有过学习,在java面试中也被提及问道过,在项目实践中也应用过,现在对hibernate和mybatis做一下对比,便于大家更好的理解和学习,使自己在做项目中更加得心应手. 第一方面:开发速度的对比 就开发速度而言,Hibernate的真正掌握要比Mybatis来得难些.Mybatis框架相对简单很容易上手,但也相对简陋些.个人觉得要用好Mybatis还是首先要先理解好Hibernate. 比起两者的开发速度,不仅仅要考虑到两者的特性及性能,更要根据项目需求

Unity5.1 新的网络引擎UNET(三) UNET NetworkManager

孙广东   2015.7.12 我们先来看看这第一个大类的 定义:http://docs.unity3d.com/ScriptReference/Networking.NetworkManager.html 直接继承自  MonoBehaviour,  还有就是被设计成了单例  singleton NetworkManager 网络管理器是一个方便的HLAPI 类,用于管理网络系统 . 对于简单的网络应用NetworkManager 网络管理器可以使用HLAPI控制 .它提供了简单的方法来  启

Hibernate 与 mybatis 区别

JAVA面试中问及HIBERNATE与 MYBATIS的对比,在这里做一下总结 我是一名java开发人员,hibernate以及mybatis都有过学习,在java面试中也被提及问道过,在项目实践中也应用过,现在对hibernate和mybatis做一下对比,便于大家更好的理解和学习,使自己在做项目中更加得心应手. 第一方面:开发速度的对比 就开发速度而言,Hibernate的真正掌握要比Mybatis来得难些.Mybatis框架相对简单很容易上手,但也相对简陋些.个人觉得要用好Mybatis还

mybatis与hibernate对比

第一方面:开发速度的对比 就开发速度而言,Hibernate的真正掌握要比Mybatis来得难些.Mybatis框架相对简单很容易上手,但也相对简陋些.个人觉得要用好Mybatis还是首先要先理解好Hibernate. 比起两者的开发速度,不仅仅要考虑到两者的特性及性能,更要根据项目需求去考虑究竟哪一个更适合项目开发,比如:一个项目中用到的复杂查询基本没有,就是简单的增删改查,这样选择hibernate效率就很快了,因为基本的sql语句已经被封装好了,根本不需要你去写sql语句,这就节省了大量的