tags:

views:

24

answers:

2

Well - exactly as the question subject states - any ideas on how you might do this?

I've been looking over the objects in System.Web.Hosting but nothing is standing out.

The reason? I'm getting one or two application errors which are typically occuring during a recycle (they happen about 25 hours apart and I've left my app pool recycle time at the default) and so I want to know if they're happening on a thread that's in the pool that's shutting down, or the one that's start(ed/ing) up.

A: 

Not sure exactly what you want to do when the appication pool recycles but if you add the below event handler to Global.asax then the code in it will run when the application is shut down.

 protected void Application_End(object sender, EventArgs e)
 {
 }
Ben Robinson
Thanks, noted. I want to know when I should take an error seriously (and display an actual error page) or perhaps re-trigger the request; might sound crazy but if I hit the url that generates the error immediately after it is raised it doesn't happen again! And the error is a null reference exception from statically held data - so that tells me it's something to do with app-startup/shutdown.
Andras Zoltan
+1  A: 

I recently stumbled across this article on Brain.Save() which talks about exactly this issue from the point of view of hosting WCF (he's Steve Maine - A program manager at Redmond on the Connected Servies Division).

They need to be able to do this when a WCF service is hosted inside Asp.Net since they need to be able to shutdown any open listeners so that the WCF engine in the new app domain will be able to open them all up again.

As the article demonstrates, the answer is to implement the IRegisteredObject interface, call ApplicationManager.CreateObject to create an instance of your object and then register it with HostingEnvironment.RegisterObject (all detailed in the MSDN documentation for the interface).

When this object's IRegisteredObject.Stop(bool) implementation is called with false as the parameter, this is notification that the app domain is being shut down and that the object should be unregistered (kind of like a global dispose) with a call to HostingEnvironment.UnregisterObject.

When it's called with true it means you've not unregistered in good time, and that if you don't Unregister immediately, it'll be done for you.

I can certainly use this mechanism to find out, when an exception occurs, if the AppDomain is being killed or not. The nature of the object in question that throws the exception means that if it's not at shutdown, it must be during initial startup.

Equally, however, I may well start looking at this persistence mechanism for some of my other more complicated static information!

Andras Zoltan