加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:27:59 所属栏目:百科 来源:网络整理
导读:我试图“测量”堆栈深度.为什么以下程序不打印任何内容? 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) { Ru
我试图“测量”堆栈深度.为什么以下程序不打印任何内容?
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);
        }
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读