RazorEngine Memory Usage

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);
}

Each time you parse a template, RazorEngine compiles an in-memory assembly.
That can get expensive.

You should re-use your templates as much as possible.


老问题,但要激活模板缓存,您必须为Parse方法提供“缓存”参数(它可以/应该是模板的路径):

return RazorViewService.Parse(File.ReadAllText(path), model, null, cache);

When you compile a template, the dynamic assemblies that are created are loaded into the current appdomain. There is no facility to unload them so as you compile more templates, the memory keeps growing.

You can use the IsolatedTemplateService in RazorEngine 3.x to get around this. What it does is load the compiled template into a new appdomain. When that appdomain is garbage collected, the template assemblies loaded into that appdomain are then collected as well. There are some limitations though--such as the inability to use dynamic models (Expando objects) or anonymous models. The model also needs to be serializable.

Check this out from the author of RazorEngine: http://www.fidelitydesign.net/?p=473

链接地址: http://www.djcxy.com/p/11168.html

上一篇: 我可以传递给一个方法的参数的数量是否有限制?

下一篇: RazorEngine内存使用情况