C# Recursion Depth - How Deep can you go

Solution 1:

I've increased the stack size during some documents recognition. It was really needed.

So you can increase stack size for thread using following code:

var stackSize = 10000000;
Thread thread = new Thread(new ThreadStart(BigRecursion), stackSize);

Thread(ThreadStart, Int32) -- Initializes a new instance of the Thread class, specifying the maximum stack size for the thread.

Source

Hope this what you need.

Solution 2:

I think you are risking problems here. It's hard to determine exactly how much stack a recursive algorithm will use. And, if you are to the point where there's some question about if there'll be enough, I'd look for another approach.

Most recursive algorithms could be rewritten to not be recursive. You can then allocate as much memory as you need and even recover gracefully if there's not enough.

Solution 3:

The default stack size is stored in the PE header.

If you spawn the thread yourself, Thread has a constructor that takes the stack size as a parameter.

However, the default .NET stack size of 1 MB should be enough for most tasks, so before you change it you should at least review the task.

Solution 4:

Even if you manage to get greater recursion depths, simply for performance reasons I would implement this algorithm without recursion. Method calls are way more expensive than iterations within a while loop. I'd strongly advise against implementing anything that requires fiddling with the default stack size.

I occasionally use recursion but only when the call depth is defined and low (as in less than 100). When creating commercial software, using recursive algorithms that have an indefinite number of iterations is completely unprofessional and likely to give you very angry customers.