【问题标题】:How do you force the IIS Application Pool to restart whenever the App Domain is reloaded?每当重新加载应用程序域时,如何强制 IIS 应用程序池重新启动?
【发布时间】:2012-08-04 14:57:22
【问题描述】:

我们有一个链接到旧本机代码的 ASP.NET MVC 4 应用程序。问题是这个遗留代码具有在启动时构建的全局静态,但由于本机代码对应用程序域一无所知,因此在重新加载应用程序域时,该代码不会重新初始化。这会导致我们的应用程序出现错误行为或崩溃,直到应用程序池进程重新启动。

因此,每当我们的应用程序的应用程序域被回收时,我想强制应用程序池进行回收。 IIS 中是否有此设置,或者在卸载域时我可以在我的应用程序中调用代码吗?

关于我的设置的一些信息,

  1. ASP.NET MVC 4 应用程序
  2. IIS 7.5,但如果需要,我可以移动到 8
  3. 我可以确保每个应用程序池有一个应用程序,因此我不会影响其他应用程序。

更新

根据下面的答案,我连接了 AppDomain 的卸载事件,并使用类似于以下的代码来回收应用程序池。

try
{
   // Find the worker process running us and from that our AppPool
   int pid = Process.GetCurrentProcess().Id;
   var manager = new ServerManager();
   WorkerProcess process = (from p in manager.WorkerProcesses where p.ProcessId == pid select p).FirstOrDefault();

   // From the name, find the AppPool and recycle it
   if ( process != null )
   {
      ApplicationPool pool = (from p in manager.ApplicationPools where p.Name == process.AppPoolName select p).FirstOrDefault();
      if ( pool != null )
      {
         log.Info( "Recycling Application Pool " + pool.Name );
         pool.Recycle();
      }
   }
}
catch ( NotImplementedException nie )
{
   log.InfoException( "Server Management functions are not implemented. We are likely running under IIS Express. Shutting down server.", nie );
   Environment.Exit( 0 );
}

【问题讨论】:

    标签: asp.net iis asp.net-mvc-4 appdomain application-pool


    【解决方案1】:

    根据您的帖子,您似乎知道何时要触发重启,所以这里有一个Restarting (Recycling) an Application Pool post 会告诉您如何操作。

    【讨论】:

    • 谢谢,这不是我所需要的,但它为我指明了正确的方向。
    • @RobProuse 那你做了什么?
    • George,我将在上面的更新中编写的代码放在启动时注册的 AppDomain 卸载事件的处理程序中。最后,我将代码转换为自托管的 ASP.NET 应用程序,以便我们可以管理应用程序和 AppDomain 的生命周期。
    【解决方案2】:

    更残酷的做法是调用 Process.GetCurrentProcess().Kill() 不是很优雅,但是如果您的网站有自己的应用程序池,并且您不在乎任何当前请求被粗暴地停止,那就非常有效!

    【讨论】:

      【解决方案3】:

      您共享的代码的简化 VB 版本。此版本使用 For 循环而不是 LINQ 查询。此外,为了使用 Microsoft.Web.Administration,您必须从 c:\windows\system32\inetsrv

      导入 DLL
      Imports System.Diagnostics
      Imports Microsoft.Web.Administration
      
      Dim pid As Integer = Process.GetCurrentProcess().Id
      Dim manager = New ServerManager()
      For Each p As WorkerProcess In manager.WorkerProcesses
          If p.ProcessId = pid Then
               For Each a As ApplicationPool In manager.ApplicationPools
                   If a.Name = p.AppPoolName Then
                       a.Recycle()
                       Exit For
                   End If
               Next
               Exit For
          End If
      Next
      

      【讨论】:

        猜你喜欢
        • 2012-03-28
        • 2023-04-01
        • 2015-08-24
        • 2018-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-19
        • 1970-01-01
        相关资源
        最近更新 更多