如果我有一个方法,我知道它可能会无限递归,但我无法可靠地预测什么条件/参数会导致它,那么在C#中做到这一点的好方法是什么:
try
{
PotentiallyInfiniteRecursiveMethod();
}
catch (StackOverflowException)
{
// Handle gracefully.
}
显然在主线程中无法做到这一点,但我已经被告知可以使用线程或AppDomain来实现,但我从未见过可靠的工作示例。有人知道如何可靠地完成这项任务吗?
如果我有一个方法,我知道它可能会无限递归,但我无法可靠地预测什么条件/参数会导致它,那么在C#中做到这一点的好方法是什么:
try
{
PotentiallyInfiniteRecursiveMethod();
}
catch (StackOverflowException)
{
// Handle gracefully.
}
显然在主线程中无法做到这一点,但我已经被告知可以使用线程或AppDomain来实现,但我从未见过可靠的工作示例。有人知道如何可靠地完成这项任务吗?
你做不到。来自MSDN
从.NET Framework版本2.0开始,try-catch块无法捕获StackOverflowException对象,并且默认情况下相应的进程会终止。因此,建议用户编写代码以检测和防止堆栈溢出。例如,如果您的应用程序依赖于递归,请使用计数器或状态条件来终止递归循环。请注意,托管公共语言运行时(CLR)的应用程序可以指定CLR卸载发生堆栈溢出异常的应用程序域并让相应的进程继续运行。有关更多信息,请参见ICLRPolicyManager接口和托管概述。
无法捕获 StackOverflowException,但您可以处理未处理的异常:
static void Main()
{
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}
static void CurrentDomain_UnhandledException
(object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;
MessageBox.Show("Whoops! Please contact the developers with the following"
+ " information:\n\n" + ex.Message + ex.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
XslCompiledTransform
对象上的Transform
方法将会出错。 - Flynn1179