Skip to main content

Count Active Sessions in ASP.Net

In order to monitor load on a site I've built and support, I wanted to add a simple counter to show how many active sessions were currently being handled by the web application.

The first technique was to use a counter variable held in the Application context. This was pretty straightforward - in global.asax increment the counter in the Session_Start event and decrement in the Session_End:


  1   Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)


  2 


  3       'Increment session count


  4       Application.Lock()


  5       Application("SessionCount") += 1


  6       Application.UnLock()


  7 


  8   End Sub


  9 


   10   Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)


   11 


   12       'Decrement session count


   13       Application.Lock()


   14       Application("SessionCount") = Application("SessionCount") - 1


   15       Application.UnLock()


   16 


   17   End Sub




Unfortunately this didn't turn out to be accurate in my case as I was using out of process session state, using State Server. This is a method of using an external service for the management of sessions, which is often a good idea as it means that user's session information will survive application restarts caused by uploading new .dlls or modifying the web.config file.

So instead made use of a performance counter, reading it's value in code for display in a web page:


  1   Private Sub DisplaySessionCount()


  2       Dim pc As PerformanceCounter


  3       Dim dblSessions As Double = 0


  4       If PerformanceCounterCategory.CounterExists("State Server Sessions Active", "ASP.NET") Then


  5           pc = New PerformanceCounter("ASP.NET", "State Server Sessions Active")


  6           dblSessions = pc.NextValue()


  7       End If


  8       lblSessionCount.Text = dblSessions.ToString()


  9   End Sub




There's a gotcha in that as it stands this will lead to a security exception. To avoid you need to add the website account (e.g. IUSR_MACHINENAME if IIS anonymous access and identity impersonate are being used), to the Performance Monitor and Perfomance Log groups under Computer Management > Local Users and Groups.

Comments

  1. You can use WMI to query the number of active sessions in a an application.
    http://www.alachisoft.com/ncache/session-index.html

    ReplyDelete
  2. `The Session_Start/Session_End way has the problem that Session_End is only called for "InProc" sessions, not if the sessions

    are stored in StateServer or SqlServer.`

    any solution for sessions in SqlServer ?

    ReplyDelete

Post a Comment