I have a "script class" in IronPython, and scripting in my app works by calling methods on its instance. I need to implement calling scripts from multiple threads. What is the correct way to do it?
I have multiple concerns:
Is
ScriptScope
thread-safe? Information is contradictory. ScriptScope's documentation says: "ScriptScope is not thread safe. Host should either lock when multiple threads could access the same module or should make a copy for each thread." However, IronRuby uses the same DLR and @JimmySchementi says that "ScriptRuntime, ScriptEngine, and ScriptScope are all thread safe, designed to be used between threads. Specifically, ScriptScope uses a thread-safe data-store, so ScriptScope can be shared between threads."If I create multiple
ScriptScope
s, that would mean executing the same initialization script multiple times. Let's suppose that I run ten Python script files, import five assemblies and on the whole execute quite a bit of code to get the "script object" ready. Is there any way to avoid the time and memory cost of running a lot of the same code for each and every thread?Is making the
ScriptScope
variable thread-static (that is, applyingThreadStaticAttribute
) and executing initialization for every thread which is utilized byTask.Run
the way to go? Or should I use aTaskScheduler
with a limit on concurrency, because the cost of multiple scopes is high?
On the whole: how to correctly implement running the same script on different arguments in multiple threads? Scripts must be executing simultaneously and must not crash due to race conditions.