tondrej / chakracore-delphi

Delphi and Free Pascal bindings and classes for Microsoft's ChakraCore library
https://tondrej.blogspot.com/search/label/chakracore
MIT License
137 stars 34 forks source link

The hosting API requires that a context be current, but there is no current context #11

Closed MrLuis closed 4 years ago

MrLuis commented 5 years ago

Hi,

When running multiple instances on a service application. In general, I evaluate a script at creation time, and that works fine. Base on external events (TCP packages), I call a function within the script using JsGetProperty to get a handle of the function, and then CallFunction passing the function handle.

When running this on a standard form-based application, it works perfectly. However when compiling the same code on a service application I get the 'The hosting API requires that a context be current, but there is no current context' error when calling JsGetProperty.

note: when testing the packages on a form application I used a single edit field and button to trigger the event. I'm not sure if the problem is because of a service application, or because the triggered events could be from any random thread. Because of this, I tried to first call JsSetCurrentContext(FContext.handle); before, but this one actually returns 'JsErrorWrongThread'.

Any suggestion is more than welcome! :)

Delphi-Win64 last update on source was yesterday night.

tondrej commented 5 years ago

As described in the Concepts the runtime is rental-threaded. What it means is that each thread needs to call JsSetCurrentContext(FContext.Handle); to "rent" the runtime and also release it by calling JsSetCurrentContext(nil); when it's done so another thread can rent it. In my experiments It worked as expected.

MrLuis commented 5 years ago

Oooohhhhh, I read the first part, but not the second... I got around by moving the creation of object from the main thread to the actual thread it will be running (so it always run on the same thread... But I'll try your way in a couple of days!

tondrej commented 5 years ago

Also see this discussion.