0

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.

Tristan Trainer
  • 2,770
  • 2
  • 17
  • 33
  • If it isn't stateful, why the lock? – Lasse V. Karlsen Apr 11 '19 at 12:44
  • 3
    Also, don't assume we know what Jint is. Either tag it (if such a tag exists) or put a link in your question. – rory.ap Apr 11 '19 at 12:47
  • 1
    Have you considered the Task class? You can hook in to the task completion with the ContinueWith method. Have the task return the Rule object it has finished with and you can add it back to a pool of available Rule objects for recycling. – Steve Todd Apr 11 '19 at 12:55
  • That's an excellent idea hadn't thought of that! Added the Jint tag as well sorry normally get all the tags right. The lock is because the Jint.Engine is stateful, however I don't care about the state of it as I'm just hooking into the function that it displays. – Tristan Trainer Apr 11 '19 at 13:17

0 Answers0