How to listen for an IIS disconnect event in ASP.NET

I have an ASP.NET static variable that flushes itself to DB every X inserts. The problem is that if I publish the application, the IIS process will be destroyed by all my static material.

How can I save it - or how can I reset it as soon as the ASP.NET application closes?

Thank you

+7
source share
4 answers

Global.asax

void Application_End(object sender, EventArgs e) { // SHUTDOWN CODE HERE } 
+10
source

It is risky to rely on application shutdown events to update the database. If IIS is restarted, recycled, or disconnected from the network, you will ignore the event.

+6
source

You cannot receive notifications that IIS is shutting down. Think about what happens if the IIS AppPool fails, or what happens if the server just loses power.

You cannot rely on ever hearing of shutdown events. If IIS wants to disconnect, it will not necessarily notify your application. I recommend that you revise your writebuffering / caching script - only store data that you might lose in memory.

+3
source

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() { // other initialization code here HostingEnvironment.RegisterObject(new HostingEnvironmentRegisteredObject()); } 
+3
source

All Articles