使用 RazorEngine 同时解析 Razor 模板 [英] Using RazorEngine to parse Razor templates concurrently

查看:22
本文介绍了使用 RazorEngine 同时解析 Razor 模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 RazorEngine 库 (http://razorengine.codeplex.com/)使用 Razor 模板语言解析字符串(不是视图)的 MVC 3 Web 应用程序.

I'm using the RazorEngine library (http://razorengine.codeplex.com/) in an MVC 3 web application to parse strings (that aren't views) using the Razor templating language.

一般来说,这很好用.但是,当多个用户同时访问解析 Razor 模板的代码时,我偶尔会看到看起来像是在内部 Razor 编译器中发生的错误(参见下面的两个).我在解释这些错误时遇到了麻烦,但我的猜测是我调用 Razor 编译器的方式不是并发安全的.

In general, this works fine. However, when multiple users are accessing code that parses Razor templates at the same time, I occasionally see errors that look like they occur in the internal Razor compiler (see two of them below). I'm having trouble interpreting these errors, but my guess is that the way I'm invoking the Razor compiler is not concurrency safe.

这是 Razor 编译器的已知问题吗?普通的 Razor 视图 (.cshtml) 如何不会遇到这个问题?有没有比将我的应用程序对 Razor.Parse 的所有调用都包装在互斥锁中更好的解决方法?

Is this a known issue with the Razor compiler? How do normal Razor views (.cshtml) not run into this problem? Is there a workaround for this better than wrapping all of my application's calls to Razor.Parse in a mutex?

我的调用代码如下,只是对Razor.Parse的一个简单包装:

My calling code is as follows, just a simple wrapper around Razor.Parse:

    protected string ParseTemplate<T>(string templateString, T model)
    {
        //This binderAssembly line is required by NUnit to prevent template compilation errors
        var binderAssembly = typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly;
        var result = Razor.Parse(templateString, model);
        return result;
    }

错误一:

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: chunkLength
at System.Text.StringBuilder.ToString()
at System.Web.Razor.Generator.RazorCodeGenerator.BlockContext.MarkEndGeneratedCode()
at System.Web.Razor.Generator.RazorCodeGenerator.WriteBlock(BlockContext block)
at System.Web.Razor.Parser.ParserContext.FlushNextOutputSpan()
at System.Web.Razor.Parser.ParserContext.StartBlock(BlockType blockType, Boolean outputCurrentBufferAsTransition)
at System.Web.Razor.Parser.ParserBase.ParseComment()
at System.Web.Razor.Parser.ParserBase.TryParseComment(SpanFactory previousSpanFactory)
at System.Web.Razor.Parser.ParserBase.ParseBlockWithOtherParser(SpanFactory previousSpanFactory, Boolean collectTransitionToken)
at System.Web.Razor.Parser.HtmlMarkupParser.TryStartCodeParser(Boolean isSingleLineMarkup, Boolean documentLevel)
at System.Web.Razor.Parser.HtmlMarkupParser.ParseRootBlock(Tuple`2 nestingSequences, Boolean caseSensitive)
at System.Web.Razor.Parser.RazorParser.Parse(LookaheadTextReader input, ParserVisitor visitor)
at System.Web.Razor.RazorTemplateEngine.GenerateCodeCore(LookaheadTextReader input, String className, String rootNamespace, String sourceFileName, Nullable`1 cancelToken)
at System.Web.Razor.RazorTemplateEngine.GenerateCode(TextReader input, String className, String rootNamespace, String sourceFileName, Nullable`1 cancelToken)
at System.Web.Razor.RazorTemplateEngine.GenerateCode(TextReader input)
at RazorEngine.Compilation.CompilerServiceBase.GetCodeCompileUnit(String className, String template, ISet`1 namespaceImports, Type templateType, Type modelType)
at RazorEngine.Compilation.DirectCompilerServiceBase.Compile(TypeContext context)
at RazorEngine.Compilation.DirectCompilerServiceBase.CompileType(TypeContext context)
at RazorEngine.Templating.TemplateService.CreateTemplate(String template, Type modelType)
at RazorEngine.Templating.TemplateService.Parse[T](String template, T model, String name)
at RazorEngine.Razor.Parse[T](String template, T model, String name)

错误二:

System.ObjectDisposedException: Cannot read from a closed TextReader.
at System.IO.StringReader.Read()
at System.Web.Razor.Text.BufferingTextReader.NextCharacter()
at System.Web.Razor.Text.BufferingTextReader.Read()
at System.Web.Razor.Parser.ParserContext.AcceptCurrent()
at System.Web.Razor.Parser.HtmlMarkupParser.ParseRootBlock(Tuple`2 nestingSequences, Boolean caseSensitive)
at System.Web.Razor.Parser.RazorParser.Parse(LookaheadTextReader input, ParserVisitor visitor)
at System.Web.Razor.RazorTemplateEngine.GenerateCodeCore(LookaheadTextReader input, String className, String rootNamespace, String sourceFileName, Nullable`1 cancelToken)
at System.Web.Razor.RazorTemplateEngine.GenerateCode(TextReader input, String className, String rootNamespace, String sourceFileName, Nullable`1 cancelToken)
at System.Web.Razor.RazorTemplateEngine.GenerateCode(TextReader input)
at RazorEngine.Compilation.CompilerServiceBase.GetCodeCompileUnit(String className, String template, ISet`1 namespaceImports, Type templateType, Type modelType)
at RazorEngine.Compilation.DirectCompilerServiceBase.Compile(TypeContext context)
at RazorEngine.Compilation.DirectCompilerServiceBase.CompileType(TypeContext context)
at RazorEngine.Templating.TemplateService.CreateTemplate(String template, Type modelType)
at RazorEngine.Templating.TemplateService.Parse[T](String template, T model, String name)
at RazorEngine.Razor.Parse[T](String template, T model, String name)

推荐答案

更新:根据他们团队的博客文章,最新版本 3.x (在 Github 上)现在是线程安全的.我没有审查其线程安全的真实性,但假设它已正确实施.请考虑此答案的其余部分仅用于历史目的.

Update: According to a blog post from their team, the latest version 3.x (on Github) is now thread-safe. I have not vetted the veracity of its thread-safety, but assume it has been implemented properly. Please consider the rest of this answer useful only for historical purposes.

从代码来看,这个项目看起来不是远程线程安全的.

Judging from the code, this project doesn't look remotely thread-safe.

Razor.Parse:

public static string Parse<T>(string template, T model, string name = null)
{
    return DefaultTemplateService.Parse<T>(template, model, name);
}

TemplateService.Parse:

public string Parse<T>(string template, T model, string name = null)
{
    var instance = GetTemplate(template, typeof(T), name);
    ...
}

TemplateService.GetTemplate:

internal ITemplate GetTemplate(string template, Type modelType, string name)
{
    if (!string.IsNullOrEmpty(name))
        if (templateCache.ContainsKey(name))
            return templateCache[name];

    var instance = CreateTemplate(template, modelType);

    if (!string.IsNullOrEmpty(name))
        if (!templateCache.ContainsKey(name))
            templateCache.Add(name, instance);

    return instance;
}

所以,Razor.Parse 是一个静态方法.DefaultTemplateServiceRazor 上的静态属性,ParseGetTemplate 是实例方法,但由于静态 DefaultTemplateService.这意味着所有线程都经过同一个实例并经过 GetTemplate.您会注意到 GetTemplate 改变状态 (templateCache) 而不获取任何锁.因此,这段代码不是线程安全的.

So, Razor.Parse is a static method. DefaultTemplateService is a static property on Razor, and Parse and GetTemplate are instance methods, but effectively invoked statically because of the static DefaultTemplateService. This means all threads go through the same instance and go through GetTemplate. You'll notice that GetTemplate mutates state (templateCache) without acquiring any locks. Therefore, this code is not threadsafe.

这篇关于使用 RazorEngine 同时解析 Razor 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆