Dr. Dobb's Journal January 1999
Threading Models and ActiveX Scripting
JScriptTest is single threaded. Most nontrivial ActiveX Scripting hosts, however, will use more than one thread and will therefore be either apartment or free threaded.
Both the JScript and VBScript engines are marked as "Both" threaded. This means that they can be used in either apartment- or free-threaded hosts without incurring any marshaling overhead. To make writing hosts simpler, the ActiveX Scripting specification defines some rules about which threads may call the scripting engine at which time. Specifically, hosts should:
- Choose a base thread (generally the thread that contains the message loop).
- Instantiate the scripting engine in the base thread.
- Call scripting engine methods only from the base thread, except where specifically allowed, as in the cases of IActiveScript::InterruptScriptThread and IActiveScript::Clone.
- Call the scripting engine's dispatch object only from the base thread.
- Ensure that the message loop runs in the base thread if a window handle is provided.
- Ensure that objects in the host's object model are only source events in the base thread.
The documentation goes on to say "none of these restrictions apply to a host that chooses to implement a free-threaded IActiveScriptSite interface and a free-threaded object model. Such a host can use the IActiveScript interface from any thread, without restriction."
Unfortunately, this is not true for the current implementations of either JScript or VBScript. Calling any methods other than IActiveScript::InterruptScriptThread and IActiveScript::Clone from any thread other than the base thread will result in an error, even in a free-threaded host that implements a free-threaded IActiveScriptSite.
The reasoning behind this is efficiency. Scripts often interact with ActiveX controls, and these controls will often be apartment threaded. If the script engine could be called from any thread at any time, it would internally have to marshal all calls to such controls. If, however, it can guarantee that any individual script is called only on a single thread, no marshaling is necessary. This does, unfortunately, mean that hosts that want to call a single script from more than one thread will have to implement their own internal marshaling scheme to ensure adherence to the aforementioned rules.
-- P.B.
Copyright © 1999, Dr. Dobb's Journal