The Application_end method in my ASP.NET MVC website is called many times weirdly almost at the same time

3.7k Views Asked by At

It is an ASP.NET MVC website. I add some log in the Application_end method.

I know there are some circumstances when the Application_end will be called, such as application pool's recycle, web.config file's change, or bin file's change. But my problem here is very weirdly.The Application_end methon in my ASP.NET MVC website is called many times weirdly almost at the same time.

Here is my code:

protected void Application_end()
    {
        FileLog.Info("The website is starting to quit...", LogType.Info);
        PersistentService.RunSignal = false;
        //To wait for pesistent action finish
        Task.WaitAll(_tasks.ToArray(), 1000 * 300);
        FileLog.Info("The website finish quit...", LogType.Info);
    }

Here is my log result: enter image description here

You can see, the Application_end is called 4 times in the same second. I guess, it can be called one time if the application pool is recycled at that time, but why 4 times?

Could anyone help? Thanks.

Edit: I notice that my application pool is with 5 worker processes at max. Is every work process's end will call Application_end method? enter image description here

2

There are 2 best solutions below

1
On BEST ANSWER

It seems that it's called when the application domain ends, so it might make sense that its called once per process:

The Application_Start and Application_End methods are special methods that do not
represent HttpApplication events. ASP.NET calls them once for the lifetime of the 
application domain, not for each HttpApplication instance.

From https://msdn.microsoft.com/en-us/library/ms178473.aspx

1
On

You are using parameter Maximum Worker Process = 5 that means there are up to 5 process serving your application. When IIS resets, all processes ends same time.