gpt4 book ai didi

c# - 在 C# 中捕获 StackOverflow 异常的通用方法是什么?

转载 作者:太空狗 更新时间:2023-10-30 00:12:34 24 4
gpt4 key购买 nike

如果我有一个我知道可能无限递归的方法,但我不能可靠地预测什么条件/参数会导致它,那么在 C# 中执行此操作的好方法是什么:

try
{
PotentiallyInfiniteRecursiveMethod();
}
catch (StackOverflowException)
{
// Handle gracefully.
}

显然在主线程中你不能这样做,但有人多次告诉我可以使用线程或 AppDomain 来做到这一点,但我从未见过一个有效的例子。有人知道这是如何可靠地完成的吗?

最佳答案

你不能。来自 MSDN

Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow. For example, if your application depends on recursion, use a counter or a state condition to terminate the recursive loop. Note that an application that hosts the common language runtime (CLR) can specify that the CLR unload the application domain where the stack overflow exception occurs and let the corresponding process continue. For more information, see ICLRPolicyManager Interface and Hosting Overview.

关于c# - 在 C# 中捕获 StackOverflow 异常的通用方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3871797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com