Search code examples
c#delegatesexpressionexpression-treesanonymous-function

Expression tree depth limitations


I'm facing a problem trying to call Compile() on the LambdaExpression of type Expression<Func<MyType, bool>> which has a depth around 400. And lesser values do not cause any problems. And I can't find anything about such kind of limitation. Can anyone clarify this? Can I increase this limit?

upd: Sorry, forgot to mention, I'm getting StackOverflowException:

An unhandled exception of type 'System.StackOverflowException' occurred in System.Core.dll {Cannot evaluate expression because the current thread is in a stack overflow state.}


Solution

  • You are legitimately running into a limit on the stack size (although I question the wisdom of a 400+ item lambda). The easiest way to bypass that is to create a new thread specifically for performing this compilation with a larger stack, using the thread constructor that takes the stack size as an argument: http://msdn.microsoft.com/en-us/library/ms149581.aspx

    Call compile in that thread and increase the stack size argument as necessary. It is in bytes I believe, which would make the default about 1048576, so start there and raise it as needed.