Wednesday, October 20, 2010

Keeping Session Alive in Asp.Net

some time we have a requirement that we want to keep our session alive. A sudden solution that come to mind is that increase the session timeout in IIS. But this solution don't work well as we might except. It create issues like we have to increase timeout also for Application Pool. Because Application Recycles itself after 30 mins if no request hit server. I am Demonstrating two Strategies here for keeping session alive.

1. Approach No 1 Using JQuery and Handler.
Simply Add a Generic Handler to your web site like "Ping.ashx" or "KeepAlive.ashx" whatever you want. (The Reason i prefer handler over aspx pages in such scenarios is because Handler are fast as compare to aspx page which has a complete life cycle to run). In this handler simply add line of code like.
Context.Response.Write(" "); /// not necessory.
Now on your aspx page add following Code


2. Using IFrame.
Create a aspx page or Handler same as above and add the following line of code
context.Response.AddHeader("Refresh", Convert.ToString(( Session.Timeout * 60 ) -120 ));
after that Add following javascript code on you page.


I hope this will help.

3 comments:

  1. shouldn't setInterval be setTimeout?

    ReplyDelete
  2. Dear JohnK
    In Javascript setTimeout and setInterval apparently perform the same task. The Techinical difference is, In setTimeout it tell browser to run a piece of code after the timespan specified passed. In setInterval The Execution start first time but the function keep control of the thread and the time span specified is used as pause between two executions.

    I hope this will clear it.
    Thanks

    ReplyDelete
  3. If you use it like this, the it should be setTimeout. If you use setInterval, then you should call it once with your function as a parameter and your function should just have your page call in it and not contain the setInterval again.

    What happens is that the first setInterval call creates an interval instance. When that instance calls a function with another setInterval call in it, now you have two instances running and so on until your threads get out of control. Here's an updated example if you want to use setInterval rather than setTimeout.

    function keepAlive() {
    $.post("KeepAlive.ashx");
    }

    $(document).ready(setInterval(keepAlive, 10000));

    ReplyDelete