asp.netiis-7

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


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.


Solution

  • 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;
           }
        }
    }