Development Tip

응용 프로그램 풀 다시 시작 (재활용)

yourdevel 2020. 11. 19. 22:08
반응형

응용 프로그램 풀 다시 시작 (재활용)


C # (. net 2)에서 IIS 응용 프로그램 풀을 어떻게 다시 시작 (재활용) 할 수 있습니까?

샘플 코드를 게시 해주시면 감사하겠습니다.


남자,

당신이 경우 IIS7 이 중지 된 경우 다음이 그것을 할 것입니다. 표시하지 않고도 다시 시작하도록 조정할 수 있다고 가정합니다.

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

IIS6 을 사용하는 경우 확실하지 않지만 web.config를 가져와 수정 된 날짜 등을 편집 할 수 있습니다. web.config를 편집하면 응용 프로그램이 다시 시작됩니다.


여기 있습니다 :

HttpRuntime.UnloadAppDomain();

이 기사가 도움이 될 것입니다.


아래 코드는 IIS6에서 작동합니다. 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();
    }
}

"시작"또는 "중지"에 대한 "재활용"을 변경할 수도 있습니다.


응용 프로그램 풀을 재활용하기 위해 코드와 약간 다른 경로를 사용했습니다. 다른 사람들이 제공 한 것과 다른 몇 가지 유의할 사항 :

1) ServerManager 개체를 올바르게 처리하기 위해 using 문을 사용했습니다.

2) 응용 프로그램을 중지하기 전에 응용 프로그램 풀이 시작되기를 기다리고 있으므로 응용 프로그램을 중지하는 데 문제가 발생하지 않습니다. 마찬가지로 시작을 시도하기 전에 앱 풀이 중지되기를 기다리고 있습니다.

3) 로컬 서버로 돌아가는 대신 실제 서버 이름을 받아들이도록 방법을 강요하고 있습니다. 왜냐하면 나는 당신이 이것을 실행하는 서버를 알아야 할 것이라고 생각했기 때문입니다.

4) 다른 이유로 중지 된 응용 프로그램 풀을 실수로 시작하지 않았는지 확인하고 이미 중지 된 응용 프로그램을 재활용하려고 할 때 발생하는 문제를 방지하기 위해 응용 프로그램을 재활용하는 대신 시작 / 중지하기로 결정했습니다. 응용 프로그램 풀.

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

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

때로는 단순한 것이 가장 좋다고 생각합니다. 그리고 다른 환경에서 더 넓은 방식으로 작업하기 위해 실제 경로를 영리한 방식으로 조정하는 것이 좋습니다. 내 솔루션은 다음과 같습니다.

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

C #에서 트릭을 수행하는 DOS 명령을 실행합니다. 위의 솔루션 중 상당수는 다양한 설정에서 작동하지 않거나 Windows의 기능을 켜야합니다 (설정에 따라 다름).


이 코드는 나를 위해 작동합니다. 응용 프로그램을 다시로드하려면 호출하십시오.

System.Web.HttpRuntime.UnloadAppDomain()

아래 방법은 IIS7 및 IIS8 모두에서 작동하는 것으로 테스트되었습니다.

Step 1 : Add reference to Microsoft.Web.Administration.dll. The file can be found in the path C:\Windows\System32\inetsrv\, or install it as NuGet Package https://www.nuget.org/packages/Microsoft.Web.Administration/

Step 2 : Add the below code

using Microsoft.Web.Administration;

Using Null-Conditional Operator

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

OR

Using if condition to check for null

var yourAppPool=new ServerManager().ApplicationPools["Your_App_Pool_Name"];
if(yourAppPool!=null)
    yourAppPool.Recycle();

Another option:

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

Seems better than UploadAppDomain which "terminates" the app while the former waits for stuff to finish its work.

참고URL : https://stackoverflow.com/questions/249927/restarting-recycling-an-application-pool

반응형