HttpApplication instances

May 18, 2008 at 8:42 PMAndre Loker

I always thought the HttpApplication class defined in global.asax would only be instantiated once for the web application. This is not the case. ASP.NET may instantiate many instances of HttpApplication as required. In fact, it will create an instance of the class for each request that is handled in parallel on the server. That is, seven requests being executed at the same time will result in at least seven instances of the application class.

Important facts:

  • Multiple HttpApplication instances can be created by ASP.NET during runtime
    • At least one for each parallel request
  • Each HttpApplication will handle a single request
    • No two parallel requests will have access to the same HttpApplication instance
    • This means that instance fields on the HttpApplication are thread safe and can be used exclusively for the current HttpRequest
  • HttpApplication instances are reused
    • The same HttpApplication instance is allowed to be used for multiple (consecutive, not concurrent) requests
    • This means that the application instance might be around for quite some time without being garbage collected. If you use instance fields that reference expensive resources you should clean up those instance fields in Application_EndRequest
  • Application_Start and Application_End are called only once per running web application. Of course, each time the application pool is recycled or the webapplication is restarted the two events are called again.
    • The default template for global.asax.cs implements Application_Start and Application_End as instance methods of Global (the class derived from HttpApplication). This is misleading as the programmer might be tempted to initialize instance fields in those event handlers. As the handlers are called only once on the first instance of the HttpApplication class all subsequently created instances of the class won't have their instance fields initialized correctly (i.e. with the semantic as implied by the Application_Start implementation)
    • Conclusion: do not set any instance fields in Application_Start or Application_End unless you don't need them for more then one (i.e. the first) request

Posted in: ASP.NET

Tags: , ,

Pingbacks and trackbacks (1)+