asp.net - 如何判断 IIS 应用程序池被回收的原因

标签 asp.net iis iis-7 asp.net-mvc-3 application-pool

背景:

我已将在我的计算机上运行的 ASP.NET MVC 3 应用程序部署到 shared hosting provider我发现一些问题似乎与应用程序池被回收有关。主机已将回收配置为在以下任何情况下发生:

  • 内存使用量超过 200MB
  • CPU 使用率超过 75%(可能持续一段时间)
  • 20 分钟空闲时间

我的开发机器上的限制更加宽松,因此我在开发过程中没有看到这样的回收。我没有共享托管盒的管理员访问权限(可以理解),因此我无法读取事件日志来了解为什么会发生这种回收。

问题:

有没有办法可以找出我的应用程序被回收的原因(例如在 Application_End 中),以便我可以记录它以帮助我进行调试?

最佳答案

如果无法访问事件日志(因为您处于共享托管环境中),您将获得的大部分信息来自 Application_End 事件并通过询问 HttpRuntime (通过反射)获取一两个私有(private)成员的值,遗憾的是这些成员没有公开暴露。

为此,请将以下代码添加到您的 Application_End 事件中:

BindingFlags staticFlags = 
    BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField;
BindingFlags instanceFlags = 
    BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField;

HttpRuntime runtime = (HttpRuntime)typeof(System.Web.HttpRuntime)
                        .InvokeMember("_theRuntime", staticFlags, null, null, null);
if(runtime != null) 
{
    string shutDownMessage = (string)runtime.GetType()
         .InvokeMember("_shutDownMessage", instanceFlags, null, runtime, null);

    string shutDownStack = (string)runtime.GetType()
         .InvokeMember("_shutDownStack", instanceFlags, null, runtime, null);

    // Log shutDownMessage & shutDownStack somewhere
}

如果我关闭或回收应用程序的应用程序池,我会看到以下内容:

HostingEnvironment initiated shutdown
HostingEnvironment caused shutdown -    
   at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
   at System.Environment.get_StackTrace()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownWithoutDemand()
   at System.Web.Hosting.PipelineRuntime.StopProcessing()

That's probably about as good as it gets.

Update:

I couldn't remember where I found this code but Drew helpfully reminded me it was from a Scott Guthrie blog post.

There are some other private members that could be useful such as:

private ApplicationShutdownReason _shutdownReason;

您可以在 .NET Reflector 中检查这些字段(如果您仍然有一份未被定时炸弹的副本)或替代方案之一 ( Open Source Alternatives to Reflector? )。

关于asp.net - 如何判断 IIS 应用程序池被回收的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5443356/

相关文章:

iis-7 - 使用 WMI 用 C# 创建 IIS 应用程序目录

c# - 在 LINQ group by procedure 之后访问 List<T> 中保存的对象属性

c# - 将单词 TOTAL 添加到 Gridview 的最后一行

c# - 多线程/异步请求并等待它们全部完成然后处理结果

asp.net - 如何强制 System.IO.Path.GetDirectoryName(字符串路径)在 Windows 环境中使用/

performance - ASP.NET Web API StreamContent 与 IIS 静态文件处理程序

c# - aspx page.pls的URL重写给我建议

windows - 为什么HTTP访问*.mp4文件会出现404错误?

asp.net-mvc - ASP.NET MVC Web 应用程序中的负载平衡。什么不能/不能做什么?

c# - ASP.Net Response.Close 问题