c# – 为什么ExecuteCodeWithGuaranteedCleanup不起作用?

我试图“测量”堆栈深度.为什么以下程序不打印任何内容
class Program
{
    private static int Depth = 0;

    static void A(object o) 
    {
        Depth++;
        A(o);
    }

    static void B(object o,bool e)
    {
        Console.WriteLine(Depth);
    }

    static void Main(string[] args)
    {
        RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(A,B,null);
    }
}

一些答案只包含来自MSDN的引用,如“从.NET Framework 2.0版开始,一个tryO catch块无法捕获StackOverflowException对象,认情况下会终止相应的进程.”相信我,有时(当有足够的堆栈空间时)它可以是cought,下面打印一些数字就好了:

class Program
{
    private static int depth = 0;

    static void A(object o)
    {
        depth++;
        if (Environment.StackTrace.Length > 8000)
            throw new StackOverflowException("Catch me if you can.");
        A(o);
    }

    static void B(object o,bool e)
    {
        Console.WriteLine(depth);
    }

    static void Main(string[] args)
    {
        RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(A,null);
    }
}

解决方法

如果你想捕获它,将它加载到另一个进程(通过远程处理回调你的进程)并让恶意代码在那里执行.另一个过程可能会终止,你可以得到一个整洁的SOE突然出现在你身边的管道末端 – 没有相当不方便的例外的不利影响.

请注意,同一进程中的单独AppDomain不会删除它.

如果您想从异常中获取堆栈跟踪,以下代码将为您提供良好的正义:

class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Recurse(0);
            }
            catch (Exception ex)
            {
                StackTrace st = new StackTrace(ex);
                // Go wild.
                Console.WriteLine(st.FrameCount);
            }
            Console.ReadLine();
        }

        static void Recurse(int counter)
        {
            if (counter >= 100)
                throw new Exception();
            Recurse(++counter);
        }
    }

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...