微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);
        }
    }

原文地址:https://www.jb51.cc/csharp/98578.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐