C# 重新启动(回收)应用程序池
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/249927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Restarting (Recycling) an Application Pool
提问by
How can I restart(recycle) IIS Application Pool from C# (.net 2)?
如何从 C# (.net 2) 重新启动(回收)IIS 应用程序池?
Appreciate if you post sample code?
感谢您发布示例代码?
采纳答案by dove
If you're on IIS7then this will do it if it is stopped. I assume you can adjust for restarting without having to be shown.
如果您使用的是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;
}
If you're on IIS6I'm not so sure, but you could try getting the web.config and editing the modified date or something. Once an edit is made to the web.config then the application will restart.
如果您使用的是IIS6,我不太确定,但您可以尝试获取 web.config 并编辑修改日期或其他内容。对 web.config 进行编辑后,应用程序将重新启动。
回答by alexandrul
回答by Wolf5
Recycle code working on IIS6:
在 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);
}
回答by Ricardo Nolde
The code below works on IIS6. Not tested in IIS7.
下面的代码适用于 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();
}
}
You can change "Recycle" for "Start" or "Stop" also.
您也可以将“回收”更改为“开始”或“停止”。
回答by Nathan Ridley
Here we go:
开始了:
HttpRuntime.UnloadAppDomain();
回答by Simply G.
Sometimes I feel that simple is best. And while I suggest that one adapts the actual path in some clever way to work on a wider way on other enviorments - my solution looks something like:
有时我觉得简单就是最好的。虽然我建议以某种聪明的方式调整实际路径,以便在其他环境中以更广泛的方式工作 - 我的解决方案看起来像:
ExecuteDosCommand(@"c:\Windows\System32\inetsrv\appcmd recycle apppool " + appPool);
From C#, run a DOS command that does the trick. Many of the solutions above does not work on various settings and/or require features on Windows to be turned on (depending on setting).
在 C# 中,运行一个 DOS 命令来解决这个问题。上述许多解决方案不适用于各种设置和/或需要打开 Windows 上的功能(取决于设置)。
回答by Spazmoose
I went a slightly different route with my code to recycle the application pool. A few things to note that are different than what others have provided:
我用我的代码走了一条稍微不同的路线来回收应用程序池。需要注意的一些事项与其他人提供的不同:
1) I used a using statement to ensure proper disposal of the ServerManager object.
1) 我使用了 using 语句来确保正确处理 ServerManager 对象。
2) I am waiting for the application pool to finish starting before stopping it, so that we don't run into any issues with trying to stop the application. Similarly, I am waiting for the app pool to finish stopping before trying to start it.
2) 我正在等待应用程序池在停止之前完成启动,这样我们就不会在尝试停止应用程序时遇到任何问题。同样,在尝试启动它之前,我正在等待应用程序池完成停止。
3) I am forcing the method to accept an actual server name instead of falling back to the local server, because I figured you should probably know what server you are running this against.
3)我强制该方法接受实际的服务器名称而不是回退到本地服务器,因为我认为您可能应该知道您正在运行的服务器。
4) I decided to start/stop the application as opposed to recycling it, so that I could make sure that we didn't accidentally start an application pool that was stopped for another reason, and to avoid issues with trying to recycle an already stopped application pool.
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);
}
}
}
回答by Fred
this code work for me. just call it to reload application.
这段代码对我有用。只需调用它即可重新加载应用程序。
System.Web.HttpRuntime.UnloadAppDomain()
回答by Kaarthikeyan
Below method is tested to be working for both IIS7 and IIS8
以下方法经测试适用于 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/
步骤 1:添加对Microsoft.Web.Administration.dll 的引用。该文件可以在路径 C:\Windows\System32\inetsrv\ 中找到,或者将其安装为 NuGet 包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
使用 if 条件检查 null
var yourAppPool=new ServerManager().ApplicationPools["Your_App_Pool_Name"];
if(yourAppPool!=null)
yourAppPool.Recycle();
回答by Alex
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.
似乎比UploadAppDomain
在前者等待东西完成其工作时“终止”应用程序更好。