gpt4 book ai didi

c# - 为什么 IIS 在循环构造函数上给出广泛的 "502.3 - Bad Gateway"错误

转载 作者:行者123 更新时间:2023-12-03 03:42:29 25 4
gpt4 key购买 nike

我确实明白为什么代码无法工作。我不明白是什么技术原因造成的,所以我们没有得到更明确的错误消息。

在开发 netcore2 应用程序时,我最终使用构造函数进行了循环引用。我的意思是,类 A 的构造函数实例化了另一个类型 B 的对象,而该对象本身又实例化了类型 A 的对象,依此类推。

这是一个简单的代码片段,用于重现循环实例化,该实例化会在 online compiler 上抛出 StackOverflowException我做了这个例子。

public class A
{
public A()
{
var b = new B();
}
}

public class B
{
public B()
{
var b = new B();
}
}

public class Program
{
public static void Main(string[] args)
{
var a = new A();
}
}

令人惊讶的是,IIS 在应用程序崩溃之前向我提供的不是 stackoverflow 异常,而是 502.3 - Bad Gateway 错误,该错误没有提供有关根本问题的太多信息。我预计像这样的循环调用是一种很容易检测到的模式,因为它不仅可以被编译器捕获,甚至可以被 VisualStudio 2017 或 Resharper Ultimate 精确定位,但没有任何警告我。

this article以及this one似乎表明问题可能是超时,但似乎不太可能,因为应用程序在两秒内崩溃。

我根本不明白为什么没有 CircularConstructionException - 这听起来很容易实现,更糟糕的是,为什么 IIS 不抛出一个常规的 StackOverflowException 就像在线编译器?

最佳答案

我相信正确的答案是这是C#的设计决定。在您的情况下,其他异常会被捕获并包装在异常页面中,而 StackOverflowException 会导致进程终止,这就是报告 502.3 响应(报告连接失败)的原因。


来自 MSDN 页面 StackOverflowException s:

In prior versions of the .NET Framework, your application could catch a StackOverflowException object (for example, to recover from unbounded recursion). However, that practice is currently discouraged because significant additional code is required to reliably catch a stack overflow exception and continue program execution.

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 the Common Language Runtime.

关于c# - 为什么 IIS 在循环构造函数上给出广泛的 "502.3 - Bad Gateway"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46817950/

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