4

Let's say we want to execute some action only once or a couple of times after web application has started and during a web request.

public class WebApp : HttpApplication
{
    public override void Init()
    {
        base.Init();

        this.BeginRequest += new EventHandler(this.OnFirstBeginRequest);
    }

    private void OnFirstBeginRequest(object sender, EventArgs e)
    {
        // do some action and if everything is OK, unbind this handler,
        // because we need it executed only once at the first web request
        this.BeginRequest -= new EventHandler(this.OnFirstBeginRequest);
    }
}

The following exception will be thrown:

Event handlers can only be bound to HttpApplication events during IHttpModule initialization.

Pero P.
  • 25,813
  • 9
  • 61
  • 85
Konstantin Tarkus
  • 37,618
  • 14
  • 135
  • 121
  • Why you don't use `Global.asax` and `Application_Start` ? – Xaqron Apr 29 '11 at 21:02
  • Just came across a similar question yesterday: [Why can event handlers can only be bound to HttpApplication events during IHttpModule initialization?](http://stackoverflow.com/q/2781346/102112). – Oleks Apr 29 '11 at 22:12
  • 1
    Xaqron, why should I? That would complicate that code sample, shifting the subject of my question to a different direction. – Konstantin Tarkus May 02 '11 at 01:30

1 Answers1

2

It wouldn't make sense to use event handlers in an HttpApplication instance to execute some code on the first request to your application, because each time a new HttpApplication instance is created it's going to rebind those events and the code in the event handlers will run again.

Multiple HttpApplication instances are created by the ASP.NET worker process. They are pooled for performance purposes, but there can definitely be more than one instance of the HttpApplication servicing requests for your web app.

Here's a pretty good article on the subject.

Kevin Babcock
  • 10,187
  • 19
  • 69
  • 89
  • 1
    Yep, and exactly for that reason I need to UNBIND an event handler which was registered inside Init() method after it has done it's job. The question remains, why ASP.NET doesn't allow to do it. – Konstantin Tarkus May 01 '11 at 08:30