本文介绍了为什么 .NET4.0 无法捕获 AccessViolationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

有趣的是,以下 C# 代码会在 .NET4.0 上崩溃,但在 .NET2.0 上运行良好.

It is really interesting that the following C# code will crash on .NET4.0 but work fine on .NET2.0.

C# 代码

class Program
{
    static void Main(string[] args)
    {
        try
        {
            ExceptionTest();
            Console.WriteLine("Done!");
        }
        catch (Exception e)
        {
            Console.WriteLine("Error !!!");
            Console.WriteLine(e.Message);
        }
    }

    [DllImport("badapp")]
    private static extern int ExceptionTest();
}

C++ 代码

extern "C" __declspec(dllexport) int ExceptionTest()
{
    IUnknown* pUnk = NULL;
    pUnk->AddRef();
    return 0;
}

如果针对 .NET2.0 编译上述 C# 代码,则一切正常.只有针对 .NET4.0 编译它才会在运行时崩溃.

If compiling the above C# code against .NET2.0, everything works fine. Only compiling it against .NET4.0 will make it crash at runtime.

我怀疑自 .NET4.0 以来系统异常捕获机制已经改变.有什么想法吗?

I'm suspecting that system exception catch mechanism has been changed since .NET4.0. Any ideas?

推荐答案

是的,它在 .NET 4 中发生了变化.您无法捕获指示损坏状态的异常.这是因为当抛出损坏的状态异常时,几乎不能保证您可以做任何事情.实际上没有理由希望状态损坏的进程继续执行.

Yes, it changed in .NET 4. You cannot catch exceptions that indicate a corrupted state. This is because there's pretty much no guarantee that you can do anything at all when a corrupted state exception is thrown. There is practically no reason to want a process with corrupted state to continue executing.

为了与旧代码兼容,您可以通过添加legacyCorruptedStateExceptionsPolicy 元素添加到 app.config.

For compatibility with older code, you can change this behaviour by adding the legacyCorruptedStateExceptionsPolicy element to app.config.

您还可以通过使用 HandleProcessCorruptedStateExceptions 属性.

这篇关于为什么 .NET4.0 无法捕获 AccessViolationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 06:22