MVC Session State Performance

Source: Internet
Author: User
Tags button type httpcontext session id

Objective

This section translates an article about session state performance issues, non-word translation.

Topic

I don't know if we used the session state feature in the real world, it's mainly used to store data when multiple requests are made in the same browser, and now we're more inclined to take advantage of the highly extensible Ajax in order to avoid the entire page refresh. But don't you know if we notice the performance problem when we use the session data to request the action method on MVC multiple times?

Place session in context (put session into the context)

In the code demonstration we first need to know how the session works: When a new request arrives at the server for the first time, it is obvious that there is no sessionid in the cookie before this time, the server will create a new session ID, by the following:

System.Web.HttpContext.Current.Session.SessionID

However, it does not mean that the server will save a session Cookie when multiple requests are sent to the server. Just save the specific requested data in the session, in other words, the ASP will first add the session cookie to the response stream, and the data that needs to be saved will be stored in the session.

So, speaking of it, it seems to have nothing to do with the topic we're talking about, what does that have to do with our performance? Asp. NET can handle multiple requests from the same browser, as follows:

In the above picture, when the browser does not make a request, it is obvious that no session data will be stored on the server, if the server stores some data in the session, a session cookie will be added to the response stream, and then all the sub-requests use the same session Cookie, which in turn waits to be processed in the form of a queue.

We can imagine a very common scenario where multiple requests to read or modify the same session value at the same time can result in inconsistent data. Next go to our topic demo time.

Code Demo

We give the following code in the controller:

    [OutputCache (Nostore = true, Duration = 0)]//Do not cache data public    class Homecontroller:controller    {public        list< ;string> boxes = new List<string> () {"Red", "green", "Blue", "Black", "gray", "yellow", "orange"};        Get:home public        ActionResult Index ()        {            return View ();        }        public string Getbox ()//randomly gets the color of the collection in        {            System.Threading.Thread.Sleep (ten);            Random rnd = new Random ();            int index = rnd. Next (0, boxes. Count);            return boxes[index];         }        Public ActionResult startsession ()//Start Session co-value        {            system.web.httpcontext.current.session["Name"] = " Chris ";            Return redirecttoaction ("Index");        }    }

Next we use ANGULARJS to make AJAX requests and other operations in the view, and we look at the code in the view:

<body ng-controller= "Asyncctrl" ng-init= "getboxes ()" > <nav role= "Navigation" class= "NavBar Navbar-default Navbar-fixed-top "> <div class=" Container-fluid "> <!--Brand and toggle get grouped for Bette R Mobile Display--<div class= "Navbar-header" > <button type= "button" data-target= " #navbarCollapse "data-toggle=" collapse "class=" Navbar-toggle "> <span class=" sr-only ">toggle na vigation</span> <span class= "Icon-bar" ></span> <span class= "ico            N-bar "></span> <span class=" Icon-bar "></span> </button> </div> <!--Collection of Nav links and other content for toggling-<div id=                    "Navbarcollapse" class= "collapse Navbar-collapse" > <ul class= "Nav navbar-nav" > <li class= "Active" >&ltA href= "#" >performace testing</a></li> <li> @Html. Actionli NK ("Start Session", "startsession") </li> <li> &L T;a class= "Links" ng-click= "getboxes ()" >not resolved</a> </li> <li > <a class= "Links" ng-click= "getboxes (True)" >Resolved</a> </li > <li> <form class= "Navbar-form" > < Label class= "checkbox" style= "margin-top:5px" > @Html. CheckBox ("Issessionnewchk", Session . Isnewsession, new {@disabled = "disabled"}) is Session new &lt                ;/label> </form> </li> </ul> <ul class= "Nav navbaR-nav navbar-right "> <li><a href=" # ">{{boxes.length}} boxes</a></li>    </ul> </div> </div> </nav> <br/><br/><br/> <div class= "Container" > <div class= "Row" > <div id= "boxescontainer" ng-repeat= "color in B Oxes track by $index "> <div class=" box "ng-class=" Color "/> </div> </di v> <br/> <div class= "Row" > <div id= "timeoccured" ng-show= "Showresults" class= " Alert "ng-class=" isresolved () "ng-bind=" timeelapsed "></div> </div> </div> <script src = "~/scripts/app.js" ></script></body>

Now let's see app.js .

Angular.module (' Asyncapp ', []). Value (' Mvcuri ', ' Http://localhost:49588/home/getbox '). Value (' Mvcurisessionresolved ', ' Http://localhost:49588/SessionResolved/getbox '). Controller (' Asyncctrl ', function ($http,        $scope, Mvcuri, mvcurisessionresolved) {$scope. boxes = [];        $scope. Showresults = false;        var Uri;            $scope. getboxes = function (resolved) {var start = new Date ();                        var counter = 300;            if (resolved) URI = mvcurisessionresolved;            else URI = Mvcuri;            Init variables $scope. boxes = [];            $scope. Showresults = false;            $scope. timeelapsed = "; for (var i = 0; i < i++) {$http. Get (URI). Success (function (data, status, Heade                        RS, config) {$scope. Boxes.push (data);                        counter--;                     if (counter = = 0) {       var time = new Date (). GetTime ()-start.gettime ();                            $scope. timeelapsed = ' time elapsed (ms): ' + time;                        $scope. Showresults = true; }}). Error (function (Error) {$scope. timeelapsed = E Rror.                        Message;            }). Finally (function () {});        }        }; $scope. isresolved = function () {return URI = = Mvcuri?        ' Alert-danger ': ' alert-success '; }    });

The above Angularjs scripts are relatively simple to describe. Next, create a controller Sessionresolvedcontroller to compare.

    [OutputCache (Nostore = true, Duration = 0)]    public class Sessionresolvedcontroller:controller    {public        list<string> boxes = new List<string> ( {"Red", "green", "Blue", "Black", "gray", "yellow", "orange"};        public string Getbox ()        {            try            {                System.Threading.Thread.Sleep (ten);                Random rnd = new Random ();                int index = rnd. Next (0, boxes. Count);                return boxes[index];            }            catch (Exception ex)            {                return "red";}}    }

At this point we look at the effect of running:

When we run the program, this check box is ticked, indicating that there is no data added to the session, then we click on the Start session to see the effect:

We are starting the start session and controlling the whole issue of 300 Ajax requests and returning random colors. We've seen it take 8722 milliseconds.

Next we click Not resolved to see how much time it takes, as follows:

It takes 8166 milliseconds and it seems to be no different from the start session. Because each request to the server has a session Cookie, all requests are processed sequentially as we described earlier, so let's do the following:

    [SessionState (sessionstatebehavior.disabled)]    public class Sessionresolvedcontroller:controller    {...}

We disable sessionstate to see the effect:

Note: The above program runs are recommended for presentation in release mode, which may be more noticeable.

Reference

ASP. NET MVC Session State performance Issue

Conclusion

When multiple requests are sent to the server at this point, a session operation will have a performance impact. We finally validated this view by setting the [sessionstate (sessionstatebehavior.disabled)] feature. However, we will not be able to get the value in session after this setting. Therefore, in the case of a large number of requests, it is recommended to use the Web API for AJAX requests, we receive AJAX requests through the Web API, we can use the data in the session to render the view or submit to the data or parameters to the MVC Controller's action method.

Thank you for taking the time to finish this article, if you think this text is good, please click on the " recommended " button, your "recommendation" is my greatest encouragement and unremitting efforts of affirmation.
This article copyright belongs to the author and the blog Park all, source website: http://www.cnblogs.com/CreateMyself/welcome you reprint, reprint article must in the article page obvious position gives the author and the original text connection, otherwise reserves the right to pursue legal responsibility and small contempt.

MVC Session State Performance

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.