Redémarrage (recyclage) D'un Pool D'applications

Comment puis-je redémarrer(recycler) le Pool D'applications IIS à partir de C# (.net 2)?

vous appréciez si vous postez un code échantillon?

59
demandé sur dove 2008-10-30 14:54:24

8 réponses

Jean,

Si vous êtes sur IIS7 alors ce sera le faire si elle est arrêtée. Je suppose que vous pouvez régler pour redémarrer sans avoir à être montré.

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

Si vous êtes sur IIS6 je ne suis pas si sûr, mais vous pourriez essayer d'obtenir le web.config et édition de la date modifiée ou quelque chose. Une fois qu'une édition est faite sur le web.config alors l'application va redémarrer.

51
répondu dove 2008-10-30 12:06:58

nous y voilà:

HttpRuntime.UnloadAppDomain();
78
répondu Nathan Ridley 2009-07-04 09:45:24

le code ci-dessous fonctionne sur IIS6. Non testé dans 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();
    }
}

vous pouvez changer" Recycle "pour" Start "ou" Stop " aussi.

7
répondu Ricardo Nolde 2009-01-30 17:14:05

j'ai suivi une voie légèrement différente avec mon code pour recycler le pool d'applications. Quelques points à noter qui sont différents de ce que d'autres ont fourni:

1) j'ai utilisé un énoncé d'utilisation pour assurer l'élimination appropriée de L'objet ServerManager.

2) j'attends que la piscine d'application ait fini de démarrer avant de l'arrêter, de sorte que nous n'ayons pas de problèmes à essayer d'arrêter l'application. De même, je suis en attente pour l'application piscine pour finir de s'arrêter avant d'essayer de commencer.

3) je force la méthode à accepter un nom de serveur réel au lieu de retomber sur le serveur local, parce que j'ai pensé que vous devriez probablement savoir sur quel serveur vous exécutez ceci.

4) j'ai décidé de démarrer / arrêter l'application au lieu de la recycler, afin de m'assurer que nous ne démarrions pas accidentellement un pool d'application qui a été arrêté pour une autre raison, et d'éviter problèmes avec essayer de recycler un bassin d'applications déjà arrêté.

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);
        }
    }
}
6
répondu Spazmoose 2015-02-17 01:49:46

Recycler code de travail sur 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
répondu Wolf5 2008-12-02 08:47:54

Parfois, je pense que simple est préférable. Et tandis que je suggère que l'on adapte le chemin réel d'une certaine manière intelligente pour travailler sur une manière plus large sur d'autres environnements - ma solution ressemble à quelque chose comme:

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

à Partir de C#, exécuter une commande DOS qui fait le tour. La plupart des solutions ci-dessus ne fonctionnent pas sur différents paramètres et/ou nécessitent des fonctionnalités sur Windows pour être activées (selon le réglage).

2
répondu Simply G. 2013-09-03 06:35:53

ce code fonctionne pour moi. appelez simplement pour recharger l'application.

System.Web.HttpRuntime.UnloadAppDomain()
0
répondu Fred 2015-12-08 11:04:02