Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For a C# AI program I use a recursive call to find the best next move (using a 30x30 Array to store the current board state). For each move I make, I want to see which of the possible moves I can make from the new board state will be best... and so on until I either reach an "end of game" position (no further moves possible in that state) or a timer stops the process and no further recursive calls are made (and the "best" known position is returned). This just to explain why I must use recursion (it is not tail recursion) and I cannot use a single (global) board state, but must search all board states possible from the current state.

(Sometimes) I get a System.StackOverflowException. Is there a way to check the available stack space before the next recursive call? Then I could just return the current state as a "best position found so far" and not make the next recursive call. I.e. when the available stack becomes too small it should also count as a base case.

The other option of course, may be to just put each recursive call in a try..catch block and handle the System.StackOverflowException by using it as a base case?

like image 827
Chavoux Luyt Avatar asked Sep 09 '12 15:09

Chavoux Luyt


1 Answers

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.

like image 189
João Angelo Avatar answered Oct 13 '22 01:10

João Angelo