microsoft / Chakra-Samples

Repository for Chakra JavaScript engine related samples.
MIT License
216 stars 84 forks source link

Single runtime with multiple contexts - disposing context and avoiding memory leak #45

Closed globeport closed 7 years ago

globeport commented 7 years ago

I am testing the chakra engine using the c# wrapper provided here. I have created a single runtime and I am then creating a new context for each script execution. (I have a requirement to run each script within a clean context). Unless I'm missing something, there doesn't seem to be a way to dispose of the context when I'm finished with it? As a result the process memory rockets up with each script invocation. At the moment I'm working around this by creating (and then disposing of) a new runtime for each script call but I imagine this creates an unnecessary (and probably quite heavy) performance overhead. It does however clean up memory!

Thanks, Stuart

liminzhu commented 7 years ago

Hey @globeport. You don't have to explicitly dispose contexts are they are subject to GC. Chakra pins the current context (specified by JsSetCurrentContext) for you, and once you switch to a different context with another JsSetCurrentContext call, the previous context can be collected unless you explicitly pin it through JsAddRef (you can negate JsAddRef with JsRelease if you wish to dispose the context later).

globeport commented 7 years ago

Thanks for clarifying liminzhu. Each time i run a new script i set the current context to a new context, and at the end i call jssetcurrentcontext to clear the context. I had suspected that the context should be garbage collected (im not adding any references to it) but this doesnt happen. If i explicitly call collectgarbage on the runtime there is no reclaim of memory. I simplified things whereby i only run one script before dallocating the context. Still the runtime seems to be hanging on to it. Hmmm well it helps to know that it should be garbage collected when the current context is changed and that there is no requirement to formally dispose of it. Ill investigate a bit more.

liminzhu commented 7 years ago

No problem @globeport. If you still can't get the contexts to be collected and can create a small repo, I'm happy to take a look.

globeport commented 7 years ago

Thanks @liminzhu. I refactored my ChakraHost a little and now everything seems to be working. Memory is being freed just fine. So I don't know what I was doing. Thanks for you help in clarifying things!

liminzhu commented 7 years ago

No problem.