C#面试题

标签 c# asp.net

这是一个面试问题,我需要帮助。

您有以下 ASP.NET 代码隐藏类:

public partial class Page1 : Page 
{
    private string _value;

    public Page1() 
    {
        if (DateTime.Now.Ticks % 10 == 0)
            _value = "Test";
    }       

    ~Page1() 
    {
        if(_value.Equals("Test"))
            _value = string.Empty;      
    }
}

只要有人请求此页面,w3wp.exe 进程就会意外终止。

  • 为什么会发生这种情况,而用户看到的是死机蓝屏(默认 ASP.NET 错误页面)?

  • 为什么托管堆上总是出现 OutOfMemoryException?

最佳答案

提示:永远不要在析构函数/终结器中抛出异常,否则您将终止运行 GC 的线程,如果没有 GC,事情可能会变得很糟糕。

虽然 .NET 1.1 对在后台线程中抛出的异常有一定的容忍度,这些异常已被消耗并且不会导致托管进程停止,但从 CLR 2.0 开始就不再如此了。 Quote from the doc :

If Finalize or an override of Finalize throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process and no active try-finally blocks or finalizers are executed. This behavior ensures process integrity if the finalizer cannot free or destroy resources.

在终结器中抛出异常是致命的。

关于C#面试题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5598334/

相关文章:

asp.net - 计算列中不同值的最快方法,包括 NULL 值

css - 将标签放在动态图像按钮的底部

c# - 从相对路径加载c#中的dll

c# - 包装 DLL - 了解导入失败的原因

c# - 排除正则表达式结果中字符串的第一个和最后一个引号

c# - 检查 asp.net 中的第二个参数

ASP.NEt 在 IE 中滚动时 Tab 键顺序丢失

c# - 单击即可创建多个 MySQL 插入(库存系统)

c# - 在 Mongo 中处理分层数据

javascript - ASP.NET C# <asp :Button type ="button"> but still acting like <asp:Button type ="submit">