C# 如何处理StackOverflowException
考虑以下代码:C# 如何处理StackOverflowException,c#,.net,wcf,stack-overflow,C#,.net,Wcf,Stack Overflow,考虑以下代码: [GlobalErrorBehaviorAttribute(typeof(GlobalErrorHandler))] public class Service1 : IService1 { public string Recursive(int value) { Recursive(value); return string.Format("You entered: {0}", value); } 这是我的GlobalEr
[GlobalErrorBehaviorAttribute(typeof(GlobalErrorHandler))]
public class Service1 : IService1
{
public string Recursive(int value)
{
Recursive(value);
return string.Format("You entered: {0}", value);
}
这是我的GlobalErrorHandler
:
public class GlobalErrorHandler : IErrorHandler
{
public bool HandleError(Exception error)
{
string path = HostingEnvironment.ApplicationPhysicalPath;
using (TextWriter tw = File.AppendText(Path.Combine(path, @"d:\\IIS.Log")))
{
if (error != null)
{
tw.WriteLine("Exception:{0}{1}Method: {2}{3}Message:{4}",
error.GetType().Name, Environment.NewLine, error.TargetSite.Name,
Environment.NewLine, error.Message + Environment.NewLine);
}
tw.Close();
}
return true;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
var newEx = new FaultException(
string.Format("Exception caught at GlobalErrorHandler{0}Method: {1}{2}Message:{3}",
Environment.NewLine, error.TargetSite.Name, Environment.NewLine, error.Message));
MessageFault msgFault = newEx.CreateMessageFault();
fault = Message.CreateMessage(version, msgFault, newEx.Action);
}
}
当我在WCF测试客户机中调用Recursive
时,我得到了这个错误。为什么我不能处理StackOverflowException
有没有办法处理这种错误?根据:
从.NET Framework 2.0开始,您无法使用try/catch块捕获StackOverflowException对象,并且默认情况下会终止相应的进程。因此,您应该编写代码来检测和防止堆栈溢出
在这种情况下,这意味着您应该主动防止异常,如果深度变低,则传入一个整数检查,然后自己抛出一个异常,如下所示:
public string Recursive(int value, int counter)
{
if (counter > MAX_RECURSION_LEVEL) throw new Exception("Too bad!");
Recursive(value, counter + 1);
return string.Format("You entered: {0}", value);
}
或者重写要使用的算法。答案是:因为规范这么说,原因是当堆栈溢出发生时,进程状态太不可靠,系统甚至无法确定您是否真的可以到达该
捕获部分谢谢。这是一个示例项目。我有一个应用程序,它有应用程序池,并且apppoll经常重新启动。我编写此代码是为了测试。我知道它已经是测试代码了。答案仍然是:预防它,就像几乎所有例外一样。