c# - (未处理AccessViolationException)如何在C#中实现HandleProcessCorruptedStateExceptions?

标签 c# visual-studio error-handling

我在运行程序约一天后遇到了一个问题,即AccessViolationException未得到处理。
(更多信息:我正在使用Visual Studio 2010)
但是,它没有说明发生此异常的位置,给了我两个选择:“确定”和“继续”。当我按OK时,什么也没发生,所以我按了继续,程序停止了调试。
当我尝试找到解决方案时,我知道可以实现HandleProcessCorruptedStateExceptions来解决此问题。但是,我不知道从哪里开始。
我是否仅将以下代码包括在内?在哪里包含这些代码?

[HandleProcessCorruptedStateExceptions] 
[SecurityCritical]
public static int Main() 
{ 
   try
     {
       // Catch any exceptions leaking out of the program CallMainProgramLoop(); 
     }
   catch (Exception e) 
       // We could be catching anything here 
     {
         // The exception we caught could have been a program error
        // or something much more serious. Regardless, we know that
        // something is not right. We'll just output the exception 
       // and exit with an error. We won't try to do any work when
       // the program or process is in an unknown state!

        System.Console.WriteLine(e.Message); 
        return 1; 
     } 

  return 0; 

}
另外,我也可以这样做legacyCorruptedStateExceptionsPolicy,但它说我应该在配置文件中输入所需的语句。在哪里可以找到配置文件?
感谢所有回复!

最佳答案

您问题的实际答案是here,我真的不应该再回答它,但是我想向您展示一些代码示例,并且我不想在注释中写它:)

在我不时的一个项目中,有一个无法预料的异常(exception)。为了捕捉它,我在Program.cs中编写了以下代码:

[STAThread]
static void Main()
{
    // add UnhandledException handler
    AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm());
}

private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
    // prepare message for user
    var message = "There was an unknown exception while running <app_name>!";
    var exception = e.ExceptionObject as Exception;

    if (exception != null)
    {
        // change message if there was actual exception
        message = $"There was an {exception.GetType().Name} exception while running <app_name>! {exception.Message}";
        // adding inner exceptions messages
        var innerException = exception.InnerException;
        while (innerException != null)
        {
            message += $"\r\n-> {innerException.GetType().Name}: {innerException.Message}";
            innerException = innerException.InnerException;
        }
#if DEBUG
        // add tracing info
        message += $"\r\n\r\n{GetStackTrace(exception)}";
#endif
    }
    if (e.IsTerminating) message += "\r\n\r\n<app_name> will be closed.";

    // showing message to the user
    MessageBox.Show(message, "Unhandled Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
#if DEBUG
private static string GetStackTrace(Exception exception)
{
    var trace = new System.Diagnostics.StackTrace(exception, fNeedFileInfo: true);
    var frames = trace.GetFrames()
        .Select((f, i) => {
            var filename = f.GetFileName();
            var methodInfo = f.GetMethod();

            var frame = $"#{i} in the method {methodInfo.DeclaringType.FullName}.{methodInfo.Name}()";
            if (filename != null) frame += $" (source file: {System.IO.Path.GetFileName(filename)}@{f.GetFileLineNumber()}:{f.GetFileColumnNumber()})";

            return frame;
        });

    return $"Full stack trace ({trace.FrameCount} frames total):\r\n{string.Join("\r\n", frames)}";
}
#endif

现在,当发生未处理的异常时-将出现一个消息框,其中显示完整的异常消息(和内部异常消息)。对于,还有完整的堆栈跟踪,在发生异常的地方调试的方法名称,行号和源文件名。

关于HandleProcessCorruptedStateExceptions

您在评论中提到了HandleProcessCorruptedStateExceptions属性。 The docs明确指出,除非绝对确定需要使用,否则不应该使用它。

Corrupted process state exceptions are exceptions that indicate that the state of a process has been corrupted. We do not recommend executing your application in this state.

By default, the common language runtime (CLR) does not deliver these exceptions to managed code, and the try/catch blocks (and other exception-handling clauses) are not invoked for them. If you are absolutely sure that you want to maintain your handling of these exceptions, you must apply the HandleProcessCorruptedStateExceptionsAttribute attribute to the method whose exception-handling clauses you want to execute. The CLR delivers the corrupted process state exception to applicable exception clauses only in methods that have both the HandleProcessCorruptedStateExceptionsAttribute and SecurityCriticalAttribute attributes.



损坏的进程状态意味着会发生一些真正的灾难性事件,并且使应用程序立即死亡更安全。如果您仍然不够害怕,可以使用上面示例中设置了Main()属性的HandleProcessCorruptedStateExceptions方法:
[STAThread]
[HandleProcessCorruptedStateExceptions, SecurityCritical]
static void Main()
{
    try
    {
        // add UnhandledException handler
        // AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
        // * in this particular case is not quite useful to handle this exceptions,
        //   because you already wrap your entire application in a try/catch block

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
    catch (Exception ex)
    {
        // handle it somehow
    }
}

关于c# - (未处理AccessViolationException)如何在C#中实现HandleProcessCorruptedStateExceptions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56105293/

相关文章:

c# - Expression.Constant(value, type) 类型未知。如何定义类型

c# - 编码UI : Why is searching for a cell so slow?

.NET Framework 更新使构建带有 "Encountered conflict between ..."警告

c++ - CGAL:加载 .off 文件后如何访问顶点颜色?

c++ - 无法捕获 std::invalid_argument

c# - ASP.NET MVC 如何在不重写 URL 的情况下处理 Application_Error 的 404 错误

flash - AS3 : ERROR 1046: Type was not found or was not a compile-time constant: Stage and TextField

c# - ASP MVC3 - 将选项标记为选中

c# - 向 CSS 文件添加一些自动版本控制。为什么我无法提取装配信息?

visual-studio - 为什么 Visual Studio 不断尝试创建 'dummy/empty' 文件?