title: Using RazorEngine to parse Razor templates concurrently
body: <p>I'm using the RazorEngine library (<a href="http://razorengine.codeplex.com/" rel="noreferrer">http://razorengine.codeplex.com/</a>) in an MVC 3 web application to parse strings (that aren't views) using the Razor templating language.</p>
  
  <p>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.</p>
  
  <p>Is this a known issue with the Razor compiler? How do normal Razor views (<code>.cshtml</code>) 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?</p>
  
  <p>My calling code is as follows, just a simple wrapper around <code>Razor.Parse</code>:</p>
  
  <pre><code>    protected string ParseTemplate&lt;T&gt;(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;
      }
  </code></pre>
  
  <p>Error one:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>Error two:</p>
  
  <pre><code>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)
  </code></pre>