Monday, 23 November 2009

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:

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

2

3'Increment session count

4 Application.Lock()

5 Application("SessionCount") += 1

6 Application.UnLock()

7

8EndSub

9

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

11

12'Decrement session count

13 Application.Lock()

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

15 Application.UnLock()

16

17EndSub

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:

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.

Andy ButlandHead of .Net for Zone/Cognizant, architecting and developing solutions primarily on .Net and using Umbraco, Sitecore and EPiServer CMS. This blog is used as a repository for various tips, tricks, issues and impressions drawn from the use of technology in website development. All words are my own.