Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Memory leak when marshalling StringWriter between AppDomains. #495

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Memory leak when marshalling StringWriter between AppDomains. #495

wants to merge 1 commit into from

Conversation

johannesg
Copy link

Attached is a small program that renders a template to a string using the extension method that uses a StringWriter internally:

        while (!Console.KeyAvailable)
        {
          var result = service.Run("TestTemplate", typeof(TemplateModel), new TemplateModel {Name = "World"});
          Console.WriteLine("Run: {0}. Result: {1}", ++counter, result.Substring(0, 20));
        }

When this loop is called when using a sandbox (IsolatedRazorEngineService), it will quite quickly run out of memory, causing OutOfMemoryException.

The reason is that the internal StringBuilder instance inside the StringWriter will not be GC:ed for several minutes because It is held by the lease manager.

I made a hack in the extension method 'WithWriter' that, instead of using StringWriter, use a MemoryStream + StreamWriter and encode it back to a String. For some reason, using a StreamWriter will not cause memory usage to rise.

I'm not sure if this is actually a bug in .NET or rather an effect of how RazorEngine overrides the management of service lifetime across AppDomains (CrossAppDomainObject).

…Writer. Use of a StreamWriter between mashalled calls removes the leak.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant