mparlak / Flee

Fast Lightweight Expression Evaluator
624 stars 119 forks source link

Support switch owner in multiple threading environment #99

Open LiPascal opened 2 years ago

LiPascal commented 2 years ago

One very common usage is the same expression used for evaluation in multiple thread environment with different paramter very frequently. As the expression string is same, we don't want to compile it every time. If it is in single thread envionment, we could replace the owner in the generated IL delegate:

class Owner  { public int Number { get; set; } }
[Test]
public void OwnerSwitchTest()
{
    var owner = new Owner() { Number = 5 };
    ExpressionContext context = new ExpressionContext(owner);
    var e1 = context.CompileGeneric<bool>("Number = 5");
    Assert.IsTrue(e1.Evaluate());
    e1.Owner = new Owner() { Number = 4 };
    Assert.IsFalse(e1.Evaluate());
}

However, as the owner replacement and evaluatation need to use an internal _myOwner to pass owner, in multiple threading environment this will fail:

//This is failed test case:
[Test]
public void MultipleOwnerTest()
{
    var owner = new Owner();
    ExpressionContext context = new ExpressionContext(owner);
    var tasks = new List<Task<bool>>();
    var e1 = context.CompileGeneric<bool>("Number % 2 = 1");
    for (int i = 0; i < 1000; ++i)
    {
        var local = i;
        var tcs = new TaskCompletionSource<bool>();
        tasks.Add(tcs.Task);
        Task.Run(() =>
        {
            e1.Owner = new Owner() { Number = local };
            tcs.SetResult(e1.Evaluate() == (local % 2 == 1));
        });
    }
    Task.WaitAll(tasks.ToArray());
    Assert.IsTrue(tasks.All(x=>x.Result));
}

One solution is to expose one overloaded method which accepts the owner:

// In Flee.InternalTypes.Expression
public object Evaluate(object owner)
{
    ValidateOwner(owner);
    return _myEvaluator(owner, _myContext, _myContext.Variables);
}
public T EvaluateGeneric(object owner)
{
    ValidateOwner(owner);
    return _myEvaluator(owner, _myContext, _myContext.Variables);
}

I tested locally with above test case and this solution works.