gpt4 book ai didi

c# - C#: Can't catch exception in unmanaged code, even with legacyCorruptedStateExceptionsPolicy and HandleProcessCorruptedStateExceptions

转载 作者:行者123 更新时间:2023-12-03 07:49:48 24 4
gpt4 key购买 nike

我在调用非托管dll的某些C#中遇到了一个令人发指的间歇性错误:

[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(',');
}

注意 HandleProcessCorruptedStateExceptions属性。我知道在.net Framework 4+中,默认行为是忽略在非托管代码中引发的错误。但是 this MSDN article建议使用该属性应强制捕获异常。

但是,不会记录任何内容,并且永远不会命中该行的断点。

我也将其放在我的App.Config中:
<runtime>
<legacyCorruptedStateExceptionsPolicy enabled="true"/>
</runtime>

作为 also suggested by MSDN。但这似乎没有什么不同。

这令人担忧,因为在这种情况下,对于开发人员而言,能够在应用程序的此部分记录错误非常重要。无论这里出现的实际错误是什么,我还能做些什么来确保在我的代码中管理DLL引发的错误?

最佳答案

万一对于搜索相同问题并关注您提到的before的同一文章的人仍然有用,我正在使用以下属性:
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]

同样在MSDN article中,您可以找到以下文本:

The HandleProcessCorruptedStateExceptionsAttribute attribute is ignored when it is encountered in partially trusted or transparent code



因此,代码的开头看起来像:
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
public string GetAddress(int searchHandle)
{
try
...

关于c# - C#: Can't catch exception in unmanaged code, even with legacyCorruptedStateExceptionsPolicy and HandleProcessCorruptedStateExceptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37394624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com