Is there a way to check available stack size before recursive call? (C#)

Actually, the system will expand the stack size dynamically, should it run out of space on the existing stack. So, even if you could test the size of the stack, it wouldn't really matter.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms686774(v=vs.85).aspx details

The system commits additional pages from the reserved stack memory as they are needed, until either the stack reaches the reserved size minus one page (which is used as a guard page to prevent stack overflow) or the system is so low on memory that the operation fails".

Which is saying that, before the recursion occurs, the stack is one size; and if the recursion causes a stack overflow, the stack is a new size when that happened.

Since you can't catch the StackOverflowException, instead of terminal recursion, you could use tail recursion. The following link provides some good detail on converting terminal recusion into tail recusion: http://www.thomaslevesque.com/2011/09/02/tail-recursion-in-c/


You could use a queue + loop (Queue<TNode> + while (queue.MoveNext())) instead of recursion and limit the size of the queue.

Or you could count open calls to the method and limit the recursion in that manner. (Count entries and exits and don't enter recursion if entries - exists > maxOpenCalls).


If you really want to go down that path you can use EnsureSufficientExecutionstack method.

As others pointed out, starting with .NET 2.0 you cannot catch a StackOverflowException, however, from the MSDN documentation you know the previous method has the following behavior:

Ensures that the remaining stack space is large enough to execute the average .NET Framework function.

When the stack is not large enough according to this method then it will throw an InsufficientExecutionStackException exception that you can catch.