microsoft / Chakra-Samples

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

Memory management using the C# hosting sample #49

Closed mortenab closed 7 years ago

mortenab commented 7 years ago

Hi, I am developing a .NET scripting framework based on the hosting sample code from here: https://github.com/Microsoft/Chakra-Samples/tree/master/Chakra%20Samples/JSRT%20Win32%20Hosting%20Samples/Legacy%20JSRT%20Samples/C%23

When stress testing the framework I started experiencing AccessViolationExceptions in Javascript function calls. By investigating a bit, I realized that I had to call AddRef() on the JavaScriptValues passed as arguments to function calls, or else the ChakraCore garbage collector might collect the arguments before actually calling the function. My solution currently looks something like this:

JavaScriptValue[] args = CreateArgs();
foreach ( var arg in args ) 
{
  arg.AddRef();
}
// call function here and release args when done

My questions are:

From the documentation: https://msdn.microsoft.com/en-us/library/dn249552(v=vs.94).aspx

The main consideration is that the JavaScript garbage collector can only see references to values in two places: its runtime’s heap, and the stack. Thus, a reference to a JavaScript value that is stored inside of another JavaScript value or in a local variable on the stack will always be seen by the garbage collector. But references stored in other locations, such as heaps managed by the host or the system, will not be seen by the garbage collector and may result in premature collection of values that are still in use by the host.

Thanks in advance,

Morten

liminzhu commented 7 years ago

Covered in a different issue. https://github.com/Microsoft/ChakraCore/issues/1033#issuecomment-263362680