我想预防或处理StackOverflowException
我从一个电话中得到的XslCompiledTransform.Transform
内的方法Xsl Editor
我在写信。问题似乎是用户可以写一个Xsl script
这是无限递归的,它只会在调用时爆炸Transform
方法。 (也就是说,问题不仅仅是典型的程序错误,而典型的程序错误通常是导致此类异常的原因。)
有没有办法检测和/或限制允许的递归次数?或者还有其他想法可以防止这段代码在我身上爆炸吗?
来自微软:
从 .NET Framework 开始
2.0 版,StackOverflowException
try-catch 无法捕获对象
块,对应的进程是
默认终止。最后,
建议用户编写代码
检测并防止堆栈
溢出。例如,如果您的
应用程序取决于递归,使用
计数器或状态条件
终止递归循环。
我假设异常发生在内部 .NET 方法中,而不是在您的代码中。
你可以做几件事。
- 编写代码来检查 xsl 是否存在无限递归,并在应用转换之前通知用户(呃)。
- 将 XslTransform 代码加载到单独的进程中(Hacky,但工作量较少)。
您可以使用 Process 类加载将转换应用到单独进程中的程序集,并在进程终止时提醒用户失败,而无需终止您的主应用程序。
编辑:我刚刚测试过,这是如何做到的:
主要流程:
// This is just an example, obviously you'll want to pass args to this.
Process p1 = new Process();
p1.StartInfo.FileName = "ApplyTransform.exe";
p1.StartInfo.UseShellExecute = false;
p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p1.Start();
p1.WaitForExit();
if (p1.ExitCode == 1)
Console.WriteLine("StackOverflow was thrown");
应用变换过程:
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
throw new StackOverflowException();
}
// We trap this, we can't save the process,
// but we can prevent the "ILLEGAL OPERATION" window
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.IsTerminating)
{
Environment.Exit(1);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)