Debugging System.AccessViolationException

System.AccessViolationException abnormality generally occurs from unmanaged code attempts to unallocated memory read or write memory.

Manufacturing error

Catch the exception is not as easy as you might think. Let's start with a simple example System.AccessViolationException process begins. The following program initiation and catch exceptions:
class Program
{
    static void Main(string[] args)
    {
        try
        {
            var intPtr = new IntPtr(1);
            Marshal.WriteByte(intPtr, 1);
        }
        catch (AccessViolationException e)
        {
            Console.WriteLine(e);
        }
    }
}
WriteByte method of the present embodiment is a throw new System.AccessViolationException. Catch exceptions only needs a normal C # batch block. Exceptions will generate the following error message is quite general:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

In most cases (at least in my experience), by using a DllImporttrigger Access violation when calling C ++ code. I remember a .NET program created in one day, will connect to the phone via the old C ++ API code. It relies heavily on the code unmanaged code call method, a necessary part of the processing AccessViolationException is written. I guess that's what you're trying to get integrated with the old buggy code results: D

This is indeed use DllImportto re-create an exception, I wrote the following very wrong C ++ code:

#include "pch.h"
#include "Violator.h"

void ViolateMe()
{
    int* data1 = 0;
    *data1 = 0;
}

Visual Studio 2019 to create even a warning when generating code:

6011: Dereferencing NULL pointer 'data1'.

From C # to call this, I use the following code:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            ViolateMe();
        }
        catch (AccessViolationException e)
        {
            Console.WriteLine(e);
        }
    }

    [DllImport(@"C:\path\to\ViolatorLib.dll")]
    private static extern int ViolateMe();
}
When you run the code, actually throws AccessViolationException, but we will never catch block is hit. There are several ways to ensure this. One is to add the attribute to andleProcessCorruptedStateExceptionsAttribute method, as follows
class Program
{
    [HandleProcessCorruptedStateExceptions]
    static void Main(string[] args)
    {
        ...
    }
    
    ...
}
The [HandleProcessCorruptedStateExceptions] added to the main process, does cause abnormal catch blog actually captured. Another method is set to true in app / will web.config legacyCorruptedStateExceptionsPolicy:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  ...
  <runtime>
    <legacyCorruptedStateExceptionsPolicy enabled="true"/>
  </runtime>
  ...
</configuration>

Microsoft seems to add this configuration is not recommended, but I do not agree. The reason they do this is that this is actually a serious error may cause the application to close. But you always want to tell the user errors, and exceptions to the error log. As for .NET Core, HandleProcessCorruptedStateExceptionsAttribute class in the framework, but does not seem to lead to the capture AccessViolationException. I'd like to hear people's experience of this in .NET Core.

This error debugging

Honestly, AccessViolationException may be debugging nightmare. In most cases, the error is generated in unmanaged code you do not have access. Let's dig into the different scenarios, discuss how the threat of an exception in each case.

When you have access to unmanaged code

Let us continue the example above. In this case, I can actually access the failure of C ++ code. If you use F11 to enter the ValueTeMeE method, you will notice just skip VisualStudio C ++ code directly to the catch block. This is because the native code debugging is disabled due to the default settings. To resolve this issue, right-click the C # Projects, click "Properties" and select the "Startup" tab. In the debugger engine below, make sure the "Enable debugging native code" (or click CTRL + t). When the project is saved and start the application, VisualStudio now in C ++ code inside interrupt:

 

You can see the exact cause of this error and variable row is a big help.

When you can not access unmanaged code

Goodfellas. You have been reading, because you can not access the code to fail, right? In this case, in addition to contact maintenance personnel code, nothing else to do. To help them, you can generate a memory dump of the application. To do this, run the application through Visual Studio, and waits for an exception occurs. And then click Debug | dump Save As. . . And name the file. Developers can use unmanaged code similar to the WinDbg tool to try to find out what happened.
Since I have already mentioned WinDbg, you might be thinking, "Why do not you check WinDbg What is the problem?" Good question. It is absolutely possible. WinDbg does save me a couple of times. However, the use of the skills required for WinDbg and a far cry from the typical .NET developers. If there is widespread demand for it, I'll write something. Now, you just need to know that you can create a memory dump process using Visual Studio.

When you use the WebBrowser control

Both Windows Forms and WPF comes with a bundled web browser component, simply called web browser. I only experienced AccessViolationException, also saw a lot of people complain about the exception in this case.
Browser component in the past is rather cumbersome. In recent years, I believe that most problems are caused by the thread issues. C # Web control is commonly used in headless snapshot generate some URL. I mean, these days how much you produce Windows Forms applications with embedded browser functionality?
When you create a WebBrowser control in the thread, be sure to set the correct ApartmentState on the thread:

var thread = new Thread(() =>
{
   var br = new WebBrowser();
   br.Navigate(url);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();

Guess you like

Origin www.cnblogs.com/yilang/p/12564158.html