Restarting (processing) the application pool

How can I restart (recycle) the IIS application pool with C # (.net 2)?

Do you know if you send sample code?

+63
c # asp.net-mvc iis application-pool
30 Oct '08 at 11:54
source share
10 answers

John

If you are on IIS7 then this will be done if it is stopped. I assume that you can configure to restart without having to display.

// Gets the application pool collection from the server. [ModuleServiceMethod(PassThrough = true)] public ArrayList GetApplicationPoolCollection() { // Use an ArrayList to transfer objects to the client. ArrayList arrayOfApplicationBags = new ArrayList(); ServerManager serverManager = new ServerManager(); ApplicationPoolCollection applicationPoolCollection = serverManager.ApplicationPools; foreach (ApplicationPool applicationPool in applicationPoolCollection) { PropertyBag applicationPoolBag = new PropertyBag(); applicationPoolBag[ServerManagerDemoGlobals.ApplicationPoolArray] = applicationPool; arrayOfApplicationBags.Add(applicationPoolBag); // If the applicationPool is stopped, restart it. if (applicationPool.State == ObjectState.Stopped) { applicationPool.Start(); } } // CommitChanges to persist the changes to the ApplicationHost.config. serverManager.CommitChanges(); return arrayOfApplicationBags; } 

If you are on IIS6 , I'm not sure, but you can try to get web.config and edit the modified date or something else. After making changes to the web.config file, the application will restart.

+52
Oct 30 '08 at 12:00
source share

Here we go:

 HttpRuntime.UnloadAppDomain(); 
+81
Jul 04 '09 at 9:45
source share

The code below runs on IIS6. Not tested in IIS7.

 using System.DirectoryServices; ... void Recycle(string appPool) { string appPoolPath = "IIS://localhost/W3SVC/AppPools/" + appPool; using (DirectoryEntry appPoolEntry = new DirectoryEntry(appPoolPath)) { appPoolEntry.Invoke("Recycle", null); appPoolEntry.Close(); } } 

You can also change “Recycle” to “Start” or “Stop”.

+7
Jan 30 '09 at 17:14
source share

I went a little different way with my code to recycle the application pool. A few comments that differ from what others have provided:

1) I used the using statement to ensure proper disposal of the ServerManager object.

2) I wait until the application pool completes before stopping it so that we don’t encounter any problems when trying to stop the application. Likewise, I wait for the application pool to complete the shutdown before trying to start it.

3) I force the method to accept the actual server name instead of returning to the local server because I decided that you probably know which server you use it on.

4) I decided to start / stop the application, and not process it, so that I could make sure that we did not accidentally start the application pool, which was stopped for another reason, and to avoid problems with the attempt to recycle the already stopped application pool.

 public static void RecycleApplicationPool(string serverName, string appPoolName) { if (!string.IsNullOrEmpty(serverName) && !string.IsNullOrEmpty(appPoolName)) { try { using (ServerManager manager = ServerManager.OpenRemote(serverName)) { ApplicationPool appPool = manager.ApplicationPools.FirstOrDefault(ap => ap.Name == appPoolName); //Don't bother trying to recycle if we don't have an app pool if (appPool != null) { //Get the current state of the app pool bool appPoolRunning = appPool.State == ObjectState.Started || appPool.State == ObjectState.Starting; bool appPoolStopped = appPool.State == ObjectState.Stopped || appPool.State == ObjectState.Stopping; //The app pool is running, so stop it first. if (appPoolRunning) { //Wait for the app to finish before trying to stop while (appPool.State == ObjectState.Starting) { System.Threading.Thread.Sleep(1000); } //Stop the app if it isn't already stopped if (appPool.State != ObjectState.Stopped) { appPool.Stop(); } appPoolStopped = true; } //Only try restart the app pool if it was running in the first place, because there may be a reason it was not started. if (appPoolStopped && appPoolRunning) { //Wait for the app to finish before trying to start while (appPool.State == ObjectState.Stopping) { System.Threading.Thread.Sleep(1000); } //Start the app appPool.Start(); } } else { throw new Exception(string.Format("An Application Pool does not exist with the name {0}.{1}", serverName, appPoolName)); } } } catch (Exception ex) { throw new Exception(string.Format("Unable to restart the application pools for {0}.{1}", serverName, appPoolName), ex.InnerException); } } } 
+7
Feb 17 '15 at 1:49
source share

Processing code running on IIS6:

  /// <summary> /// Get a list of available Application Pools /// </summary> /// <returns></returns> public static List<string> HentAppPools() { List<string> list = new List<string>(); DirectoryEntry W3SVC = new DirectoryEntry("IIS://LocalHost/w3svc", "", ""); foreach (DirectoryEntry Site in W3SVC.Children) { if (Site.Name == "AppPools") { foreach (DirectoryEntry child in Site.Children) { list.Add(child.Name); } } } return list; } /// <summary> /// Recycle an application pool /// </summary> /// <param name="IIsApplicationPool"></param> public static void RecycleAppPool(string IIsApplicationPool) { ManagementScope scope = new ManagementScope(@"\\localhost\root\MicrosoftIISv2"); scope.Connect(); ManagementObject appPool = new ManagementObject(scope, new ManagementPath("IIsApplicationPool.Name='W3SVC/AppPools/" + IIsApplicationPool + "'"), null); appPool.InvokeMethod("Recycle", null, null); } 
+5
Dec 02 '08 at 8:47
source share

Sometimes I feel that it’s easy. And although I suggest that someone adapt the actual path in some smart way to work more widely on other conditions - my solution looks something like this:

 ExecuteDosCommand(@"c:\Windows\System32\inetsrv\appcmd recycle apppool " + appPool); 

From C #, run a DOS command that does the trick. Many of the above solutions do not work with various settings and / or require the inclusion of Windows functions (depending on the settings).

+2
03 Sep '13 at 6:35
source share

this code works for me. just call him to restart the application.

 System.Web.HttpRuntime.UnloadAppDomain() 
+2
Dec 08 '15 at 11:04
source share

The method below has been tested for functionality for both IIS7 and IIS8.

Step 1: Add the link to Microsoft.Web.Administration.dll . The file can be found on the path C: \ Windows \ System32 \ inetsrv \ or installed as a NuGet package https://www.nuget.org/packages/Microsoft.Web.Administration/

Step 2: Add the code below

 using Microsoft.Web.Administration; 

Using the Null Conditional Operator

 new ServerManager().ApplicationPools["Your_App_Pool_Name"]?.Recycle(); 

OR

Using if condition to check for zero

 var yourAppPool=new ServerManager().ApplicationPools["Your_App_Pool_Name"]; if(yourAppPool!=null) yourAppPool.Recycle(); 
+1
Nov 22 '18 at 12:47
source share

Another variant:

 System.Web.Hosting.HostingEnvironment.InitiateShutdown(); 

It seems to be better than UploadAppDomain which "closes" the application, while the former expects the material to complete its work.

0
Jul 17 '19 at 14:12
source share



All Articles