Is using the `Marshal` static class in otherwise normal C# code unwise?

血红的双手。 提交于 2020-03-10 04:40:48

问题


I have a whole sequence of interlinked questions. I would like to know answers for all of them independantly, so *yes*, some of them appear to be X-Y questions; but I do want to know the solution to them anyway!. See end of question for list of other questions in this set.


For reasons that aren't relevant to this specific question I've ended up in an event handler, triggered by a catch block in some library code.

I want to know why my EventHandler triggered, but I don't seem to get told that by the EventHandler (some might describe this as a flaw in the EventHandler.)

In a last ditch attempt to access any possible Exception Context I run this code:

    var pointers = Marshal.GetExceptionPointers();
    var code = Marshal.GetExceptionCode();
    if (code != 0 || pointers != IntPtr.Zero)
    {
        var ex = Marshal.GetExceptionForHR(code, pointers);
        _logger.Fatal(ex, "Marshal exception.");
    }

Is this a good idea? Is this safe, in general?

I particularly ask, because I've discovered that in some cases the .GetExceptionForHR() line is through a AccessViolationException! Which seems to be generally considered to be a BadSign(TM)

Is this class just inherently very low-level and kinda unsafe?

Have I mis-used the class?

Is there something odd going on elsewhere in my code which is causing the problem?


Other questions in this problem set.
  • C#: How do I prevent a pipe reading error, when closing the exe on one end of a DuplexChannel connected by Named Pipes?
  • Ascertain reason for Channel Fault in WCF+NamedPipes
  • Is using the `Marshal` static class in otherwise normal C# code unwise?
  • Is there a way to predict that `Marshal.GetExceptionForHR(code, pointers)` would throw an `AccessViolationException`
  • Is this a suitable use of `HandleProcessCorruptedStateExceptions`

来源:https://stackoverflow.com/questions/60424803/is-using-the-marshal-static-class-in-otherwise-normal-c-sharp-code-unwise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!