I have created a windows service to build and send emails. I am using the Razor Engine to parse the email templates. I am using a dynamic ExpandoObject to create the model.
My problem is when each email is created and sent the memory is increasing but it is never been released. I have profiled the service with Ants Memory profiler(I haven't used this before) but it is showing the following results:
With Razor Engine
Parsing 200 emails with Razor.Parse(text,model)
Generation 1: 12.9kb
Generation 2: 15.88mb
Large Object Heap: 290.9kb
Unused memory allocated to .NET: 3.375mb
Unmanaged: 69.51mb
Total number of memory fragments: 197
No Razor Engine
Returning 200 emails unparsed text.
Generation 1: 13.87kb
Generation 2: 3.798mb
Large Object Heap: 95.58kb
Unused memory allocated to .NET: 4.583mb
Unmanaged: 44.58mb
Total number of memory fragments: 7
With Razor the biggest generation 2 instances are:
System.Reflection.Emit __FixUpData[] - 2,447,640 live bytes, 3,138 instances
Has anyone any idea why the objects aren't being released and the Generation 2 is growing? Is there a way to have a new instance of the RazorEngine each time I want to parse a template and when its finished it will not be referenced and will go to the GC.
Ive tried creating a new instance of Template service each time I parse a template but this hasnt made a difference
using (ITemplateService templateService = new TemplateService())
{
result = templateService.Parse<ExpandoObject>(text, model);
}
Parse()
caches the template. What I've ended up doing is usingRazor.GetTemplate()
and callingRun()
on the returnedITemplate
instance. Still to see how much memory the assemblies take, but there should only be one assembly per template if it is cached properly. – StatedResolve
method does in fact cache templates. You will not be able to negate the memory usage by the assemblies as they cannot be unloaded from the appdomain, but this shouldn't be enough to cause issue. The increased size of the Gen2 collection is trickier. It may just be a side effect of the intensive task of compiling the templates. I haven't used Ants profiler, but I would poke around to see how and why things are created, and maybe you'll find a memory leak, or maybe you'll find that it is just using that much memory out of necessity. – Stated