Random ASP.NET AppDomain Restarts

Are you having a problem with apparently random application restarts in your ASP.NET application?  Does your session information mystically disappear with no discernable pattern?  Well, the following may help you out.

One of the things that ASP.NET does to help make it easier for developers to modify running web sites is to keep an eye on files that are part of the virtual directory.  If you drop a new version of a DLL into the bin directory, it takes effect from the next request on.  If you make a change to an ASPX file, it too is detected and becomes 'live' with any subsequent request.  No question that this is useful functionality.

A little known fact about this process is that ASP.NET is also aware of the amount of memory that maintaining two versions of the same assembly takes.  If changes were allowed to be made without a restart, eventually it could become detrimental to the overall performance ogf ASP.NET. To combat this, ASP.NET also tracks the number of files that are changed and after a certain number, performs an Application Restart.  As with any other restart, this causes the current session information to be lost.  By default, the number of changes before a restate is 15.  To modify this, you can change the numRecompilesBeforeApprestart attribute in the machine.config file.

While all of this is useful information, there is a small twist that can make our life more difficult.  The files that ASP.NET is watching while looking for a change is not limited to those with an .aspx extension. In fact, it is any file in the virtual directory.  Also, the name of the setting implies that the Recompiles are what is being counted.  It's not.  What is being counted is the number of files that change.  Or, more accurately, the number of changes to any file in the virtual directory. 

How can this cause problems?  What if you were to put a log file into the virtual directory of a web site.  What if that log file were opened and kept open while the information was written to it.  When that log file filled up, it is closed and a new one opened.  Of course, this close counts as a file change.  That would mean that after 15 log files are created (assuming no other changes to the web site), the virtual directory would automatically reset.  And since the amount of information written to the log file will be different depending on which pages/web methods are called, the frequency of the reset is dependent on factors that are not immediately apparent.  Imagine the joy of trying to discover why ASP.NET applications are being randomly reset without the benefit of this blog.

The moral of this story:  Don't put any non-static files into an ASP.NET virtual directory. My good deed for the day is done.