Why would Application_Init fire twice when starting debugging in VS2008/Casini?

扶醉桌前 提交于 2019-12-06 04:44:36

问题


Why would Application_Init fire twice when starting debugging in VS2008/Casini?

Yeah, It's happening in global.asax. Seems fairly random though, only happens once in a while.


回答1:


I assume you're referring the the Global.asax file in an ASP.NET MVC application. Notice that your global.asax extends System.Web.HttpApplication eg:

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        // (snip)
    }

    protected void Application_Init()
    {
        // Why is this running twice?
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
    }
}

Basically multiple HttpApplication instances are being instantiated to serve multiple incoming HTTP requests. Once the request is finished, the HttpApplication instance goes back into a pool to be reused again, similar to database connection pooling.

You can't predict how many HttpApplication instances will be created, basically the ASP.NET worker process will create as many as it needs to fulfill demand from HTTP requests hitting your web app. Your Application_Init() is getting called twice because 2 HttpApplication instances are being created, even though it's just you running your website. It could be that you have references to other server-side resources in your HTML being pulled in (JavaScript files, CSS etc.), or maybe an Ajax Request.

If you want to guarantee code is only run once, then put it in the Application_Start() method in your Global.asax. Or use a Bootstrapper



来源:https://stackoverflow.com/questions/3306845/why-would-application-init-fire-twice-when-starting-debugging-in-vs2008-casini

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!