tags:

views:

447

answers:

2

I want to know the amount concurrent sessions at a given time. But with spiders and load-balancers and perhaps influences that do not know about, how safe is it to do this in global asax:

void Session_Start(object sender, EventArgs e)
{
  counter++;
}

void Session_End(object sender, EventArgs e)
{
  counter--;
}

Any tips?

+1  A: 

If you are keeping the session stored in a database server or a state server, the Session_End event won't be fired. Else, I think there should be no issues.

Also while incrementing/decrementing a counter, you'll have to obtain a lock on an object like this -

lock(<some shared object>)
{
    counter++;
}

You can also try taking a look at this.

Kirtan
Locking on the `global.asax` application object? It's an absolute no-no in an ASP.NET app!
Mehrdad Afshari
+2  A: 

At very least, this solution has a threading problem (beside other problems that might affect you as you mentioned and I won't cover):

The increment and decrement task should be done in an atomic way using Interlocked.Increment and Interlocked.Decrement methods rather than ++ or --.

Mehrdad Afshari
Changed the code snippet now.
Kirtan