Attacktive
Attacktive

Reputation: 617

A StackOverflowException occurs on System.Diagnotics.StackTrace()

I've been writing a web application targeted to .NET framework v3.5 with Visual Studio 2013.

Indirect recursion in it someties cause a StackOverflowException so I wrote a method which checks if the stack overflows.

public static void CheckStackOverflow() {
    StackTrace stackTrace = new StackTrace();
    StackDepth = stackTrace.GetFrames().Length;
    if(StackDepth > MAXIMUM_STACK_DEPTH) {
        throw new StackOverflowException("StackOverflow detected.");
    }
}

The problem is that a StackOverflowException occurs at the first line, i.e. new StackTrace(), so I cannot take care of it.

I know that calling to StackTrace() also deepens the stack by a couple of levels, so I understand this can happen. However, there is some food for thought:

  1. Opting for Visual Studio(ASP.NET) Development Server(hereinafter Cassini) in Visual Studio 2012 got no problem, so my IIS settings or something like that is a suspect.
  2. The stack, at the time the exception occured, was NOT really deep enough.
  3. This only happens on debugging. Regardless of the configuration(i.e. Debug/Release).

Edit: I tried to changed IIS Express settings and it made no differences. Also, Trying Local IIS option got no luck, either. So,

if(RunningWithVisualStudio) { // Start Debugging or Without Debugging
    if(UsingCassini) {
        throw new StackOrverflowException("A catchable exception."); // expected
    } else {
        throw new StackOverflowException("I cannot catch this dang exception.");
    }
} else { // publish on the identical ApplicationPool.
    throw new StackOrverflowException("A catchable exception."); // expected
}

I thought I'd made mistakes configuring IIS Express but now I'm totally lost.

Upvotes: 1

Views: 550

Answers (1)

Attacktive
Attacktive

Reputation: 617

Here are what I did as workaround:

  1. I added below to .csproj file to define the current version of IDE. image
  2. Defined DEBUG constant
  3. added conditions using preprocessor directives.

    public static void CheckStackOverflow() {
        StackTrace stackTrace = new StackTrace();
        StackDepth = stackTrace.GetFrames().Length;
        int threashold;
    #if (VISUAL_STUDIO_12 && DEBUG)
        threshold = MAXIMUM_STACK_DEPTH_FOR_VS12; // set to be a "safe" integer
    #else
        threshold = MAXIMUM_STACK_DEPTH; // the one in common use
    #endif
        if(StackDepth > threashold) {
            throw new StackOverflowException("StackOverflow detected.");
        }
    }
    

    Where the constnat MAXIMUM_STACK_DEPTH_FOR_VS12 is the manually-found-greatest number that causes no problem.

    Now, I can debug and publish the app without changing anything but still love to hear your opinions.

Upvotes: 1

Related Questions