为什么 HttpApplication 构造函数被多次调用
有人可以解释为什么从 HttpApplication 派生的自定义类的构造函数在应用程序启动时被多次调用吗?
我的代码结构如下:
- 我在 global.asax 中的 Global 类派生自 CustomApp 类。
- CustomApp 类派生自 HttpApplication 类
Global 类在启动时创建,但是当我在构造函数中放置断点时,它会被调用几次! 我认为应该只创建一个 Application 类实例?
我错了吗?
UPD:Web 服务器确实可以创建多个 HttpApplication 实例来处理同时传入的多个请求。 当您在 HttpApplication 后代的构造函数中放置断点时,这一点变得尤其明显。 来自客户端的多个请求(http 内容、CSS 文件等)将等待处理,并且为了服务每个请求,Web 服务器将创建 HttpApp 的新实例。 因此,在编写应用程序初始化逻辑时请注意这一点。
Can somebody explain why the constructor of a custom class derived from HttpApplication is called several times upon application startup?
My code structure is the following:
- My Global class in global.asax derives from CustomApp class.
- The CustomApp class derives from HttpApplication class
The Global class is created at startup, but when I place a breakpoint in the constructor, it is invoked several times! I thought there should be only one instance of Application class created?
Am I wrong?
UPD: the web server can indeed create several HttpApplication instances to process multiple requests coming in at the same time. This becomes especially apparent when you place a breakpoint in the constructor of your HttpApplication descendant. Several requests will be pending from the client (http content, CSS files, etc) and to serve each of them the web server will create new instances of HttpApp. So, beware of this, when writing the application initialization logic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信 ASP.NET 运行时可能会为每个应用程序域创建多个 HttpApplication。 因此 HttpApplication.Init 和 Ctor 可能会被多次调用。
如果您希望初始化代码仅运行一次,则应使用 Application_Start 事件,每个应用程序仅调用该事件一次。
I believe the ASP.NET runtime may create more than one HttpApplication per application domain. So HttpApplication.Init and the Ctor may get called more than once.
If you want to have initialization code that only runs once, you should use the Application_Start event which will only be called once per app.
请查看帖子ASP.NET 中的global.asax - 它解释了为什么有多个 HttpApplication 实例。 基本上有两个池:特殊池和普通池。 普通池包含请求使用的 HttpApplication 实例(每个请求都有自己的 HttpApplication 实例)。 特殊池包含用于应用程序级事件(如 Application_Start、Application_Error)的 HttpApplication 对象。
Please have a look at a post global.asax in ASP.NET - it explains why there are multiple instances of the HttpApplication. Basically there are two pools: special and normal. Normal pool contains instances of the HttpApplication which are used by the requests (each requests has its own HttpApplication instance). Special pool contains HttpApplication objects used for application-level events (like Application_Start, Application_Error).