gpt4 book ai didi

c# - Marshal.ThrowExceptionForHR 抛出 NotSupportedException

转载 作者:太空宇宙 更新时间:2023-11-03 11:38:15 25 4
gpt4 key购买 nike

我使用以下模式将 win32 异常转换为 .NET 异常。

var result = A_KERNEL32_PINVOKE_CALL();
if (result == 0)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}

为了完整性,pinvoke 调用是以下之一:LoadLibrary、GetProcAddress、SetWindowsHookEx。

这在大多数情况下都运行良好,抛出像这样的异常:

System.ArgumentException: Argument out of range.

at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)

但有时我会遇到以下异常:

System.NotSupportedException: This Stream does not support seek operations.

at System.Net.ConnectStream.get_Position()

at System.Net.WebClient.WebClientWriteStream.get_Position()

at System.Drawing.UnsafeNativeMethods.ComStreamFromDataStream.Seek(Int64 offset, Int32 origin)

at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)

我想不出这个异常(exception)的原因。请注意,堆栈跟踪不像第一个异常那样以 ThrowExceptionForHRInternal 开头。因此,我认为这可能是 ThrowExceptionForHR 方法本身的一个异常(exception)。

编辑:请注意,我没有直接调用任何 Stream 方法。但是,代码是在线程池线程中执行的,因此同一线程中可能还有其他代码使用 Stream 方法。

有什么解决这个问题的建议吗?

更新:我刚刚发现,堆栈跟踪

at System.Net.ConnectStream.get_Position()

at System.Net.WebClient.WebClientWriteStream.get_Position()

at System.Drawing.UnsafeNativeMethods.ComStreamFromDataStream.Seek(Int64 offset, Int32 origin)

属于对 Image.Save(Stream, Format) 的调用。捕获了 NotSupportedException。这些代码和平是完全独立的,但也许它们是在同一个线程池线程上执行的。

那么为什么这个异常会影响我在另一个方法中的代码呢?

最佳答案

到目前为止,我认为我误用了 Marshal.ThrowExceptionForHR() 方法。我想它不打算与 Win32 调用一起使用。我对该行为的解释是,该函数使用当前线程的上下文信息来收集有关异常的更多详细信息。 See this blog对于类似的问题。

在我的例子中,这个问题可以通过创建我自己的 ThrowExceptionForWin32ErrorCode(errorCode) 方法来解决。

如果您有更好的解决方案,请继续回答。

关于c# - Marshal.ThrowExceptionForHR 抛出 NotSupportedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5540593/

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