1

I'm currently working on a web application based on ASP.Net. I need to do some treatments when the application is stopped or is dying.

In the HttpApplication inherited class, I know that I can define some event handler methods, notabily :

  • Application_Error(object sender, EventArgs e)
  • Application_End(object sender, EventArgs e)

I wondered if I must put my code on the Application_End method AND the Application_Error method, or if the Application_End is fired even on error.

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
Oreste Viron
  • 3,592
  • 3
  • 22
  • 34
  • 1
    [See here](https://stackoverflow.com/questions/288350/application-end-global-asax) – Zer0 Feb 21 '19 at 16:48

2 Answers2

1

It should be sufficient to simply put your code in the Application_end method, because this method will be called no matter what if the app is terminated. (including termation by error)

Application_EndRequest is the only event that is guaranteed to be raised in every request, because a request can be short-circuited. For example, if two modules handle the Application_BeginRequest event and the first one throws an exception, the Application_BeginRequest event will not be called for the second module. However, the Application_EndRequest method is always called to allow the application to clean up resources.

Also your try catch blocks should catch any errors that would end the app.

https://learn.microsoft.com/en-us/previous-versions/aspnet/ms178473(v%3dvs.100)

Joey Phillips
  • 1,543
  • 2
  • 14
  • 22
1

From ASP.NET Application Life Cycle Overview:

Application_Error can be raised at any phase in the application life cycle.

while

Application_End [is] called once per lifetime of the application before the application is unloaded.

I would use the second one.

note that it'll not be called is the application is dying because of a StackoverflowException nor an OutOfMemoryException

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142