Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

Commented Issue: Memory leak using delegates [48]

0
0
Hi,

It seems V8 engines are not garbage collected if a script uses a host delegate.

```
public class MyClass
{
}

static void DelegateTest()
{
List<WeakReference> enginesWithObject = new List<WeakReference>();
List<WeakReference> enginesWithDelegate = new List<WeakReference>();

for (int i = 0; i < 50; i++)
{
using (var engine = new V8ScriptEngine())
{
engine.AddHostType("MyClass", typeof(MyClass));
engine.Execute("var myClass = new MyClass();");
enginesWithObject.Add(new WeakReference(engine));
}

using (var engine = new V8ScriptEngine())
{
engine.AddHostType("Action", typeof(Action));
engine.Execute("var action = new Action(function(){});");
enginesWithDelegate.Add(new WeakReference(engine));
}
}

// Force garbage collection
GC.Collect();

int enginesWithObjectCnt = 0, enginesWithDelegateCnt = 0;

foreach (var item in enginesWithObject)
{
if (item.IsAlive)
{
enginesWithObjectCnt++;
}
}

foreach (var item in enginesWithDelegate)
{
if (item.IsAlive)
{
enginesWithDelegateCnt++;
}
}
Console.WriteLine("{0} of {1} engines with objects are alive", enginesWithObjectCnt, enginesWithObject.Count);
Console.WriteLine("{0} of {1} engines with delegates are alive", enginesWithDelegateCnt, enginesWithDelegate.Count);
}

```

Note - I'm using latest ClearScript version from 01 June 14.
After run I get:

0 of 50 engines with objects are alive
50 of 50 engines with delegates are alive


Assuming this issue is fixed, what is more recommended to use for a script callback:
use a dynamic call to a script function (not type safe) or to create a host delegate (requiring an additional host call) and call it from host.

Thanks in advance,
Ron




Comments: Fixed in [ClearScript 5.4](https://clearscript.codeplex.com/releases/view/135637).

Viewing all articles
Browse latest Browse all 2297