开发者

Why is there no way to unbind an HttpApplication event handler out of IHttpModule initialization scope

开发者 https://www.devze.com 2023-03-01 10:45 出处:网络
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.

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.Beg开发者_运维技巧inRequest += 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号