ExpressionTree Compile()方法生成stackoverflow异常

时间:2013-01-03 18:00:18

标签: c# expression-trees

我有一个gridview,我们可以通过不同的标准进行过滤。每个标准都是表达式。我有一个场景,我可以有超过一千个标准,导致我的表达式在调用Compile方法时抛出一个StackOverflow。

我仍然是使用表达式树btw的初学者。

这是我为重现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();

我的问题是:有没有办法“减少”这个表达式或任何其他阻止堆栈溢出的解决方案?

由于

注意:这是调试器中表达式的样子:

(SomeEntity.OrderID == "42")) 
OrElse (SomeEntity.OrderID == "42")) 
OrElse (SomeEntity.OrderID == "42")) 
OrElse (SomeEntity.OrderID == "42")) 
OrElse (SomeEntity.OrderID == "42")) 
x20000

1 个答案:

答案 0 :(得分:5)

我刚刚成功测试了这个代码达到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();
    }
}