Site icon Ryadel

ASP.NET C# - How to Recycle a .NET Web Application's App Pool programmatically

ASP.NET C# - How to Recycle a .NET Web Application's App Pool programmatically

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 GUI and 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 Application recycle it's very own app pool!

Here's the code snippet we can use to achieve such result:

I took this code from this StackOverflow thread and 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 the Microsoft.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:

ASP.NET C# - How to Recycle a .NET Web Application's App Pool programmatically

That's about it: happy recycling!

 

Exit mobile version