Reputation: 9603
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?
Upvotes: 1
Views: 1802
Reputation: 806
In case is still helpful for anyone searching for the same issues and following the same article that you mentioned before I'm using the attributes: [HandleProcessCorruptedStateExceptions] [SecurityCritical]
Also in this MSDN article you can find this text:
The HandleProcessCorruptedStateExceptionsAttribute attribute is ignored when it is encountered in partially trusted or transparent code
So the beginning of your code would look like:
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
public string GetAddress(int searchHandle)
{
try
...
Upvotes: 2