Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application_End being called too early/frequently

I am using a temporary database in a project that is disposed on Application_End:

protected void Application_End() {
    if (_db != null) _db.Dispose();
}

The problem is that Application_End seems to be called frequently whilst I am browsing through my web project - it seems that when I edit an object in the db, the change is successfully made, the database is disposed, and by the time I am redirected to the index - a new db has been created and shows the unchanged object as if nothing had happened.

Shouldn't Application_End only being called when the session is ended or after a certain amount of idle time?

Could anyone tell me how I may be able to ensure that Application_End is only called when I am actually finished using the application?

like image 716
DevDave Avatar asked Dec 21 '22 03:12

DevDave


1 Answers

The problem is that Application_End seems to be called frequently whilst I am browsing through my web project

That happens when the AppDomain is unloaded. While you are debugging it will happen everytime you recompile your project which is normal because everytime you recompile an assembly in the bin folder is being regenerated and ASP.NET simply recycles the application domain.

When you deploy your application in IIS it will happen more rarely, only when IIS decides to recycle the application. It might happen under different circumstances: a certain period of inactivity, CPU/memory thresholds are reached, ...

Shouldn't Application_End only being called when the session is ended or after a certain amount of idle time?

No, Application_End has nothing to do with user sessions. It is called at the end of the life of the application domain.

Could anyone tell me how I may be able to ensure that Application_End is only called when I am actually finished using the application?

That's the case: the Application_End is called by the ASP.NET runtime when the application domain is ready to be unloaded.

So if you want to avoid this from happening you should use a persistent database and not an in-memory storage. If you use an in-memory storage then you are tied to the lifetime of your application which as you have already noticed could be extremely short.

like image 89
Darin Dimitrov Avatar answered Jan 12 '23 08:01

Darin Dimitrov