As already mentioned, it is strongly discouraged that the application save large data during Application_End , as this can be caused when the application pool is closed, and not at the beginning of its closure. This is explained in more detail (but still short) here .
If you still want to catch the closure of the application pool for all cases that do not kill it, you can do the following:
Dirty way
1) Shutdown time limit - IIS Manager → Application Pools → -> Advanced Settings ... → Group of process models → Shutdown Time Limit (second)
2) Create a thread / task in the application to work twice as often as the shutdown time limit, to make sure that the shutdown state can be detected. This thread should
i) check if application pool is closed
public bool IsShuttingDown() { return System.Web.Hosting.HostingEnvironment.ShutdownReason != ApplicationShutdownReason.None; }
ii) if closure is on, do your stuff. Make sure that the material is run only once.
More correct way (as indicated here )
1) Create a class that implements IRegisteredObject
public class HostingEnvironmentRegisteredObject : IRegisteredObject { // this is called both when shutting down starts and when it ends public void Stop(bool immediate) { if (immediate) return; // shutting down code here // there will about Shutting down time limit seconds to do the work } }
2) Register your object ( Global.asax.cs )
protected void Application_Start() {
Alexei
source share