背景:
我已将在我的计算机上运行的 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/