Skip to content

How to handle exceeded heap size in async code? #369

@dalibor-florian

Description

@dalibor-florian

Hello,
i am trying to handle case when script exceeds memory limit.

For synchronous version of script it works like charm, when allocation meets the limit engine throws ScriptEngineException with expected message.

         [Test]
        public void MemoryLimitInSyncCode() 
        {
            using var engine = new V8ScriptEngine();
            engine.MaxRuntimeHeapSize = new UIntPtr(5 * 1024 * 1024);

            //throws Microsoft.ClearScript.ScriptEngineException: The V8 runtime has exceeded its memory limit
            Assert.Throws<ScriptEngineException>(() =>
                engine.Execute(
                    @"(function () {
                        let x = {};

                        for (let i = 0; i < 10 * 1024 * 1024; i++) {
                            x = {next: x};
                        }
                    })();")
            );
        }

In case of async code i can't figure out how to find out if the memory has been exceeded.
I would expect that the behaviour would be the same.
When i tried it, i end up with stucked script execution.

        [Test]
        public void MemoryLimitInAsyncCode()
        {
            using var engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableTaskPromiseConversion);
            engine.MaxRuntimeHeapSize = new UIntPtr(5 * 1024 * 1024);
            engine.AddHostType(typeof(Task));

           var xxx =  Assert.ThrowsAsync<ScriptEngineException>(async () =>
                await (Task)engine.Evaluate(
                    @"(async function () {
                        let x = {};

                        for (let i = 0; i < 10 * 1024 * 1024; i++) {
                            if ((i % 20000) === 0) await Task.Delay(5);
                            x = {next: x};
                        }
                    })();")
            );
        }

Am i missing something? Is there some way how to handle this kind of errors?

tested on

  • ClearScript 7.2.3
  • .net 6.0.202

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions