简体   繁体   English

IIS模块:Init()在网站中仅被调用一次?

[英]IIS module: Init() is called only once in a website?

I need to add an IIS module for some processing. 我需要添加IIS模块进行某些处理。 Here is my module: 这是我的模块:

namespace MyNamespace
{
    public class MyModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            //I hope to do some work here ONLY once for all requests

            context.ReleaseRequestState += new EventHandler(myHandler);
        }

        #endregion

        public void myHandler(Object source, EventArgs e)
        {
            //do some work...
        }
    }
}

I need to do some resources-consuming work in the Init() method. 我需要在Init()方法中做一些耗资源的工作。 I HOPE that Init is called ONLY once in a website and is called again only when the website is restarted in IIS Manager. 我希望Init仅在网站中被调用一次,并且仅当在IIS管理器中重新启动网站时才再次调用它。

Can an expert in this tell me whether Init() works as I hope for? 专家可以告诉我Init()是否按我的期望工作?

Thanks! 谢谢!

For ANY requests being carried out, it will always call this method so no, it is not for the first time the app pool spins up. 对于正在执行的任何请求,它将始终调用此方法,因此不会,这不是应用程序池第一次启动。 What you may wish to do is have a static variable in there to see if it truly is the first time its been hit and if not, carry on with what you need otherwise ignore it. 您可能希望做的是在其中有一个静态变量,以查看它是否真的是第一次被击中,如果不是,请继续执行您需要的操作,否则将其忽略。 ensure you lock around the portion of code when you are setting the variable to true. 将变量设置为true时,请确保锁定代码部分。

Remember, IIS has application pools which websites use (generally speaking). 请记住,IIS具有网站使用的应用程序池(通常而言)。 There will be multiple concurrent requests coming into IIS to process and what happens? 会有多个并发请求进入IIS进行处理,会发生什么? The app pool executes to serve the request to the website therefore multiple "hits" will be executed for the Init() for the HttpModule but once per application, if that makes sense. 应用程序池执行以将请求提供给网站,因此将为HttpModule的Init()执行多个“匹配”,但每个应用程序执行一次,如果可以的话。

Every one of them initializes their own list of modules. 他们每个人都会初始化自己的模块列表。

you DO have the option of using the Application_Start event in the global asax which will only ever execute once per application (when the app pool spins up and the request is being submitted) - perhaps you can use this for your needs, which would be a better option. 您可以选择在全局asax中使用Application_Start事件,该事件只会在每个应用程序中执行一次(当应用程序池旋转且正在提交请求时)-也许您可以使用它来满足您的需求,这将是更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM