I have some code currently that is calling a method on an object in excess of 1,000,000 times. This code section currently takes about 2minutes to run. This method also has a lock within it that contains the long running piece of code so simple Parallel execution will not work to shorten the execution time.
class Rule
{
private readonly Jint.Engine _rule;
private readonly object _ruleLock;
public Rule(Jint.Engine rule)
{
this._rule = rule;
this._ruleLock = new object();
}
public void InvokeRule(object source, object target)
{
lock (_ruleLock)
{
_rule.Invoke("rule", source, target);
}
}
}
I can however make multiple instances of this object with the same rule code since the code inside is just a calculation and not stateful. However generating multiple instances also has further time impacts since the Jint.Engine.Execute() takes a relatively long time to run as well.
If multiple instances are created for the same rule I also want to ensure that an only one instance is used.
Is there a way to create something similar to this:
var rulesOfSameKind = new List<Rule>{
new Rule(new Jint.Engine().Execute(commonJSText)),
new Rule(new Jint.Engine().Execute(commonJSText))
}
return rules.OfSameKind.First(rule => rule.IsNotRunning).InvokeRule(source, target);
A bit hard to explain what I mean but I'm basically looking for either a way to check if a thread is locked or running and try the next one and return a value from the first thread to be able to run.