Tuesday, February 21, 2012

How to check if the users are online or offline

Many developers tend to use ‘Session_End’ event to mark a user as ‘Offline’, but this may not be a good idea, because there are no one-to-one mappings between an ASP.Net session and a user. For example if a user opens 2 separate instances of Internet Explorer (e.g. 2 separate IE processes) on his workstation, he can have 2 ASP.Net sessions open. The ‘Session_End’ event of one of the session does not necessarily mean that the user is offline, they can still be using the website.
In addition, ‘Session_End’ event is only available in the ‘InProc’ session mode. If you are trying to store session states in the State Server or SQL Server, ‘Session_End’ event, it will never fire.
I would suggest using the last visiting time as the ideal approach.
Membership helps build the user database and there is a convenient approach to get it via Membership.GetUser(stringuserName).IsOnline.
If you don’t use Membership, you can use the method below which uses the same principle in Membership:
In the application, you can define a global dictionary membershipDictionary to store the information about users online and offline.
Use an AJAX Timer (or simply XmlHttpRequest in client side JavaScript) in the pages to update theLastVisitTime of the user and store it into membershipDictionary at intervals.
From time to time, visit the dictionary membershipDictionary to filter out the idle users (who have not visited the page for a long time) and also retrieve information on how many users are still online.  Regular maintenance can be done in a separate thread or a server-based timer. Please also be aware of thread synchronization issues.


  1. Hi,

    Very nice information. It helps me a lot.