Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically recycle a .net web app's own apppool?

Tags:

asp.net

iis-7

I have a complex server application that uses Nhibernate and Linq2SQL. About 3 times per day the Linq2sql code generates a "value cannot be null" exception. Once this happens, the code will always generate the exception. Diagnosis and solving the root cause will be lengthy and will introduce instability.

The current "fix" is to recyle the app pool every hour. However, the service is down from the point the problem happens until the recycle occurs. I want the web service to catch the exception and recycle it's own app pool. I want all other web requests to be honored until they are completed.

Edit: The fault is on both servers on a load balanced web farm. Clients do not switch from one server to the other just because this code crashes.

like image 607
Brian Leeming Avatar asked Feb 27 '12 18:02

Brian Leeming


People also ask

Does Web config recycle app pool?

Yes. It will be recycled.

What happens when application pool is recycled?

What is application pool recycling in IIS? Recycling means that the worker process that handles requests for that application pool is terminated and a new one is started. This is generally done to avoid unstable states that can lead to application crashes, hangs, or memory leaks.

What is the difference between IISreset and app pool recycle?

IISreset resets all application pools. Application pools are used to seperate processes. In earlier versions we always had to reset IIS, and so resetting ALL websites. When resetting an Application pool, only the websites configured to use that application pool are reset.


1 Answers

The following code will recycle the current site's app pool. You need to add a reference to Microsoft.Web.Administration

using (ServerManager iisManager = new ServerManager())
{
    SiteCollection sites = iisManager.Sites;
    foreach (Site site in sites)
    {
       if (site.Name == HostingEnvironment.SiteName) 
       {
         iisManager.ApplicationPools[site.Applications["/"].ApplicationPoolName].Recycle();
         break;
       }
    }
}
like image 152
Sebastian Brand Avatar answered Sep 25 '22 13:09

Sebastian Brand