title: Counting anonymous and logged in users - ASP.NET website
body: <p>I would like to implement reliable user counter. Currently I'm using session variables. Here is a look on my implementation:</p>
  
  <pre><code>void Application_Start(object sender, EventArgs e) 
  {
      // Code that runs on application startup
      Application["OnlineUsers"] = 0;
      Application["LoggedInUsers"] = 0;
  }
  
  void Session_Start(object sender, EventArgs e) 
  {
      // Code that runs when a new session is started
      Application.Lock();
      Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
      Application.UnLock();
  }
  
  void Session_End(object sender, EventArgs e) 
  {
      Application.Lock();
      if ((int)Application["OnlineUsers"] &gt; 0)
      {
          Application["OnlineUsers"] = (int) Application["OnlineUsers"] - 1;
      }
      Application.UnLock();
  }
  
  protected void Login1_LoggedIn(object sender, EventArgs e)
  {
      Application.Lock();
      Application["LoggedInUsers"] = (int)Application["LoggedInUsers"] + 1;
      Application.UnLock();
  }
  
  protected void LoginStatus1_LoggedOut(object sender, EventArgs e)
  {
      Application.Lock();
      if ((int)Application["LoggedInUsers"] &gt; 0)
      {
          Application["LoggedInUsers"] = (int) Application["LoggedInUsers"] - 1;
      }
      Application.UnLock();
  }
  </code></pre>
  
  <p>Downsides of that approach are well known. I couldn't find anything more accurate. Can you help me, please?</p>