Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support switch owner in multiple threading environment #99

Open
LiPascal opened this issue Jul 14, 2022 · 0 comments
Open

Support switch owner in multiple threading environment #99

LiPascal opened this issue Jul 14, 2022 · 0 comments

Comments

@LiPascal
Copy link

LiPascal commented Jul 14, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant