1

the number of visitor will increase by click, but every time when i close my browser, the number of visitor never decreased

my testing step

1)click f5 on my browser, number of visitor increased by 1

2)open another browser ,number of visitor increased again, current number of visitor is 2

3)open 1 more browser, total number of visitor now is 3

4)closed 1 broweser, by right the number of visitor should decreased by 1

5)i clicked refresh on opened browser

6)the existed browser should total number of visitor =3

7)total number of visitor never decreased =(

     private static int member = 0;
     private static int visitor = 0;
void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup

    Application["Member"] = member;



   Application["Visitor"]=visitor;




}



void Session_Start(object sender, EventArgs e) 
{
    // Code that runs when a new session is started
    visitor += 1;
    Application.Lock();

    Application["Visitor"] = visitor;

    Application.UnLock();


}

   void Session_End(object sender, EventArgs e) 
{
    // Code that runs when a session ends. 
    // Note: The Session_End event is raised only when the sessionstate mode
    // is set to InProc in the Web.config file. If session mode is set to StateServer 
    // or SQLServer, the event is not raised.


    visitor -= 1;

    Application.Lock();

    Application["Visitor"] = visitor;

    Application.UnLock();




}
Chee mun Low
  • 107
  • 10
  • possible duplicate of [Session_End does not fire?](http://stackoverflow.com/questions/4813462/session-end-does-not-fire) – Ian Mercer Feb 09 '12 at 05:20

2 Answers2

0

Closing a browser window will not end a session, since no request is actually sent to the server when that happens. Sessions only end when a user has not had any activity on their session for whatever session timeout period you set.

In theory, you could capture the window closing in javascript, then issue an AJAX request to a handler you've setup, and have that handler end the session. But that's not the default behaviour, and frankly I don't think it's even desirable.

Since you seem interested in maintaining a list of "active" users, you may just want to set the session timeout to be something very low (maybe 1 minute.)

dlev
  • 48,024
  • 5
  • 125
  • 132
0

You should not use static variables and ApplicationState at the same time.

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup

   Application["Visitor"]=0;
}

void Session_Start(object sender, EventArgs e) 
{
    Application.Lock();
    Application["Visitor"] = ((int)Application["Visitor"]) + 1;
    Application.UnLock();
}

void Session_Start(object sender, EventArgs e) 
{
    Application.Lock();
    Application["Visitor"] = ((int)Application["Visitor"]) - 1;
    Application.UnLock();
}

And also see what dlev said in the other answer

evpo
  • 2,436
  • 16
  • 23