C#: Can't catch exception in unmanaged code, even with legacyCorruptedStateExceptionsPolicy and HandleProcessCorruptedStateExceptions
<p>I've got an infuriatingly intermittent error in some C# that's calling up to an unmanaged dll:</p>

<pre><code>[DllImport(DLL,SetLastError = true, CharSet = CharSet.Ansi)]
public static extern int Q_GetLine(int SearchHandle, int LineNumber, StringBuilder Buffer, int BufferLength); 

[HandleProcessCorruptedStateExceptions]
public string GetAddress(int searchHandle)
{
    try
    {
        StringBuilder addressBuffer = new StringBuilder();

        for (int i = 0; i &lt; 5; i++)
        {
            .Q_GetLine(searchHandle, i, addressBuffer, 2000); // errors here
            returnAddress += string.Format("{0},", addressBuffer.ToString());
        }
    }
    catch(Exception ex)
    {
        _logger.Error(ex, "error in GetAddress");
    }

    return returnAddress.TrimEnd(',');
}
</code></pre>

<p>Note the <code>HandleProcessCorruptedStateExceptions</code> attribute. I'm aware that in .net framework 4+, the default behavior is to ignore errors thrown in unmanaged code. However <a href="https://msdn.microsoft.com/en-us/magazine/dd419661.aspx" rel="nofollow">this MSDN article</a> suggests that using that attribute should force the exception to be caught.</p>

<p>However, nothing is logged and a breakpoint at that line is never hit.</p>

<p>I have also put this in my App.Config:</p>

<pre><code>&lt;runtime&gt;
    &lt;legacyCorruptedStateExceptionsPolicy enabled="true"/&gt;
&lt;/runtime&gt;
</code></pre>

<p>As <a href="https://msdn.microsoft.com/en-us/library/dd638517.aspx" rel="nofollow">also suggested by MSDN</a>. But it seems to make no difference.</p>

<p>This is worrying because in this scenario, it's important for the developers to be able to log errors in this part of the application. Regardless of the actual bug that's rearing up here, what else can I do to ensure that errors thrown by the DLL are managed in my code? </p>