ExpressionTree Compile()方法生成一个stackoverflow异常
本文关键字:一个 stackoverflow 异常 Compile 方法 ExpressionTree | 更新日期: 2023-09-27 17:50:30
我有一个gridview,我们可以按不同的标准过滤。每个标准是一个表达式。我有一个场景,我可以有超过1000个条件,导致我的表达式在调用Compile方法时抛出StackOverflow。
我仍然是使用表达式树的初学者。
下面是我用来重现stackoverflow的示例。
var param = Expression.Parameter(typeof(SomeEntity), "SomeEntity");
Expression finalExpression = Expression.Default(typeof(bool));
for (int i = 0; i < 20000; i++) // Create 20000 expressions
{
var left = Expression.Property(param, "OrderID");
var right = Expression.Constant(42.ToString());
var expression = BinaryExpression.Equal(left, right);
finalExpression = Expression.OrElse(finalExpression, expression);
}
var hello = Expression.Lambda(finalExpression, param);
hello.Compile();
我的问题是:有没有一种方法来"减少"这个表达式或任何其他解决方案,防止stackoverflow ?
感谢注意:下面是在调试器中的表达式:
(SomeEntity.OrderID == "42"))
OrElse (SomeEntity.OrderID == "42"))
OrElse (SomeEntity.OrderID == "42"))
OrElse (SomeEntity.OrderID == "42"))
OrElse (SomeEntity.OrderID == "42"))
x20000
我刚刚成功地测试了这段代码,最多有1,000,000个条件没有堆栈溢出-我怀疑它可以处理尽可能多的条件,尽管
当在lambda表达式上调用Compile
时,将递归向下遍历表达式树来编译它;非常深的树(像这样)需要很多很多的堆栈帧来完成——因此StackOverflowException
。
我在下面所做的是在编译表达式并将其推入已经生成的条件集合之前,只接受固定数量的条件(由MaxPredicateConditionCount
设置)。如果预生成表达式的集合达到最大值,则将它们组合成一个新表达式,依此类推。这样,我们就可以限制编译表达式所需的递归深度(通过分段进行)。
public class PredicateBuilder<TParameter>
{
private const int MaxPredicateConditionCount = 500;
private readonly List<Expression<Func<TParameter, bool>>> _existingPredicates = new List<Expression<Func<TParameter, bool>>>(MaxPredicateConditionCount);
private readonly ParameterExpression _parameter = Expression.Parameter(typeof(TParameter));
private Expression<Func<TParameter, bool>> _expression;
private Expression _workingPredicate;
private int _workingPredicateConditionCount;
public bool Built { get; private set; }
public Expression<Func<TParameter, bool>> LambdaExpression
{
get
{
if (!Built)
{
return null;
}
return _expression;
}
}
public void AddCondition<TValue>(string propertyName, TValue value)
{
if (Built)
{
throw new InvalidOperationException("Predicate has already been built");
}
var property = Expression.Property(_parameter, propertyName);
var constant = Expression.Constant(value, typeof(TValue));
var equality = Expression.Equal(property, constant);
if (_workingPredicate == null)
{
_workingPredicate = equality;
}
else
{
if (MaxPredicateConditionCount < ++_workingPredicateConditionCount)
{
var compiledWorking = Expression.Lambda<Func<TParameter, bool>>(_workingPredicate, _parameter).Compile();
_existingPredicates.Add(p => compiledWorking(p));
if (_existingPredicates.Count + 1 > MaxPredicateConditionCount)
{
var compiled = BuildExistingPredicates().Compile();
_existingPredicates.Clear();
_existingPredicates.Add(p => compiled(p));
}
_workingPredicate = equality;
_workingPredicateConditionCount = 0;
}
else
{
_workingPredicate = Expression.OrElse(_workingPredicate, equality);
}
}
}
private Expression<Func<TParameter, bool>> BuildExistingPredicates()
{
Expression compileTemp = Expression.Invoke(_existingPredicates[0], _parameter);
for (var i = 1; i < _existingPredicates.Count; ++i)
{
var nextCall = Expression.Invoke(_existingPredicates[i], _parameter);
compileTemp = Expression.OrElse(compileTemp, nextCall);
}
return Expression.Lambda<Func<TParameter, bool>>(compileTemp, _parameter);
}
public void Build()
{
Built = true;
//There were no conditions, assume true
if (_workingPredicate == null)
{
_expression = x => true;
return;
}
_existingPredicates.Add(Expression.Lambda<Func<TParameter, bool>>(_workingPredicate, _parameter));
_expression = BuildExistingPredicates();
_existingPredicates.Clear();
_workingPredicate = null;
_workingPredicateConditionCount = 0;
}
public Func<TParameter, bool> Compile()
{
if (!Built)
{
Build();
}
return _expression.Compile();
}
}
例子实体
public class SomeEntity
{
public string OrderID { get; set; }
}
使用class Program
{
static void Main()
{
var builder = new PredicateBuilder<SomeEntity>();
for (int i = 0; i < 1000000; i++) // Create 1,000,000 expressions
{
builder.AddCondition("OrderID", "42");
Console.Title = i.ToString();
}
builder.Compile();
}
}