4

Having read this article (and others) on .NET reliability features, I am led to believe that the following code should handle StackOverflowExceptions:

class Program
{
    private static int s_exitCode = -1;

    static int Main(string[] args)
    {
        RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(DoStuff, Cleanup, null);
        return s_exitCode;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    static void DoStuff(object userdata)
    {
        DoStuff(userdata);
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    static void Cleanup(object userData, bool exceptionThrown)
    {
        s_exitCode = 0;
    }
}

I have sited the above code in a console application and have also included the following entry in the app's config file:

<runtime>
  <legacyUnhandledExceptionPolicy enabled="1" />
</runtime>

I start it via a Process.Start() call from another application. However, in spite of all this, the process crashes, returning an exit code of -2147023895. And despite a lot of research and tinkering, I am no closer to finding out how to get this to work.

Any advice gratefully received, thanks.

Chris.

Azhar
  • 20,500
  • 38
  • 146
  • 211
Chris Ward
  • 708
  • 7
  • 19
  • 2
    You cannot bypass the hard-coded response to SO in .NET 2.0 and up, it terminates the process without recourse. – Hans Passant Nov 06 '10 at 14:35
  • So how might, say, SQL Server handle a stack overflow? My problem is that I am developing a hosting app for third-party components and it would be easy for any such component to crash my host by simply calling a method recursively, as shown above. – Chris Ward Nov 06 '10 at 14:41
  • possible duplicate of [C# catch a stack overflow exception](http://stackoverflow.com/questions/1599219/c-catch-a-stack-overflow-exception) – Pieter van Ginkel Nov 06 '10 at 14:46
  • 2
    This is a really good question. There is a lot of conflicting information in official documentation concerning the behavior of `ExecuteCodeWithGuaranteedCleanup`. – Brian Gideon Dec 15 '11 at 20:43
  • @Chris, SQL Server handles it by using the ICLRPolicyManager on the CLR hosting API and sets it to `EClrUnhandledException.eHostDeterminedPolicy`. The links you mention in your post seem to indicate that you can force this behavior in .NET 2.0+, but I did similar tests and apparently the extra guards don't protect against an SO. – Abel Jan 06 '13 at 14:42
  • It seems that only Jeffrey Richter has a final word on it, saying that even in the above scenario's, FailFast (called by the SO exception) cannot be canceled: http://books.google.nl/books?id=QMdCf_mm55cC&pg=PT1016&lpg=PT1016&source=bl&ots=V942WGDtFy&sig=I8shxrKexuEKnJPvQf7Cqzck6SE&hl=en&sa=X&ei=NYnpUI-BI8-S0QX6q4GgAw&redir_esc=y – Abel Jan 06 '13 at 14:50

0 Answers0