I've got an infuriatingly intermittent error in some C# that's calling up to an unmanaged dll:
[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 < 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(',');
}
Note the HandleProcessCorruptedStateExceptions
attribute. I'm aware that in .net framework 4+, the default behavior is to ignore errors thrown in unmanaged code. However this MSDN article suggests that using that attribute should force the exception to be caught.
However, nothing is logged and a breakpoint at that line is never hit.
I have also put this in my App.Config:
<runtime>
<legacyCorruptedStateExceptionsPolicy enabled="true"/>
</runtime>
As also suggested by MSDN. But it seems to make no difference.
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?