If you’re working with ASP.NET Web Application published on IIS Web Servers you most likely already know what an Application Pool (aka App Pool) is: in a nuthsell, Application Pools allow you to isolate your web applications from one another, even if they are running on the same server. This way, if there is an error in one app, it won’t take down other applications. Additionally, applications pools allow you to separate different apps which require different levels of security.
For further info about App Pools I strongly suggest to take a look at this TechNet article: for a more practical overview and some valuable configuration code samples I also suggest this great post on the developer.com website, which basically explains everything you need to know about them.
By reading the above resources you will find that Application Pools can be periodically recycled to avoid unstable states that can lead to application crashes, hangs, or memory leaks. The App Pool’s recycling behaviour can be configured using the IIS Manager GUIand can be expressed in minutes, specific time of day and so on. You can also manually recycle an Application Pool from the GUI by using the Recycle… option, available by right-cliking on the application pool itself and also in the right column of the IIS Manager interface.
What if we want to programmatically recycle an Application Pool from a C# Application? Doing that is rather easy, even from Web Applications – providing that they do have extended permissions. Surprisingly enough, we can even make a Web Applicationrecycle it’s very own app pool!
Here’s the code snippet we can use to achieve such result:
/// Recycles a web site Application Pool (including the current web site).
/// Requires to reference Microsoft.Web.Administration and System.Web.Hosting.
/// IMPORTANT: The IIS user requires extended permissions to recycle application pool(s).
/// <param name="siteName">The site name: leave it NULL to recycle the current site's App Pool.</param>
/// <returns>TRUE if the site's App Pool has been recycled; FALSE if no site has been found with the given name.</returns>
public static bool RecycleApplicationPool(string siteName = null)
if (siteName == null) siteName = HostingEnvironment.ApplicationHost.GetSiteName();
using (ServerManager iisManager = new ServerManager())
SiteCollection sites = iisManager.Sites;
foreach (Site site in sites)
if (site.Name == siteName)
I took this code from this StackOverflow threadand slightly modified it so that I could use that to recycle any Application Pool available.
As the code comment suggests, we will need to add a reference to theMicrosoft.Web.Administration and System.Web.Hosting namespaces. In order to do that, we need to use the Add Reference…feature of our Visual Studio project and add an explicit reference to the Microsoft.Web.Administration assembly:
That’s about it: happy recycling!