Take compiled script over two engine instances

Oct 23, 2013 at 8:04 AM
Hi,

I'm looking for the most effective way of compile/use a script within a server environment and I tried to take a compiled script over two instances:
        [Test]
        public void TakeOverScript()
        {
            string script = "Console.WriteLine(item)";
            V8Script compiledscript = null;

            using (var engine = new V8ScriptEngine())
            {
                engine.AddHostObject("item", new TestItem("first instance"));
                engine.AddHostType("Console", typeof(Console));
                compiledscript = engine.Compile(script);
            }

            using (var engine = new V8ScriptEngine())
            {
                engine.AddHostObject("item", new TestItem("second instance"));
                engine.AddHostType("Console", typeof(Console));
                engine.Evaluate(compiledscript);
            }
        }

    public class TestItem
    {
        private string _value;

        public TestItem(string value)
        {
            _value = value;
        }

        public override string ToString()
        {
            return _value;
        }
    }
But it fails. Does that mean that a compiled script is always bound to a specific instance of the engine or do I something wrong?

Best regards,
Torsten
Coordinator
Oct 23, 2013 at 12:03 PM
Hi Torsten!

A compiled script is bound to a specific instance of the V8 runtime. The V8ScriptEngine constructor creates a separate runtime for each engine instance. To create multiple engine instances that share a runtime instance, use V8Runtime.CreateScriptEngine():
[Test]
public void TakeOverScript()
{
    string script = "Console.WriteLine(item)";
    V8Script compiledscript = null;

    using (var runtime = new V8Runtime())
    {
        using (var engine = runtime.CreateScriptEngine())
        {
            engine.AddHostObject("item", new TestItem("first instance"));
            engine.AddHostType("Console", typeof(Console));
            compiledscript = engine.Compile(script);
        }

        using (var engine = runtime.CreateScriptEngine())
        {
            engine.AddHostObject("item", new TestItem("second instance"));
            engine.AddHostType("Console", typeof(Console));
            engine.Evaluate(compiledscript);
        }
    }
}
Keep in mind that each runtime instance is protected by an exclusive lock, so multiple engine instances created in this manner cannot execute scripts simultaneously.

Cheers!