title: ASP.NET MVC: Exception rendering view in new thread
body: <p>I want to create a process in my ASP.NET application that I trigger manually and will send a bunch of emails to my users. Since this process takes a while I am creating a new thread to send these messages and prevent having timeouts in my web app. (I know this is error prone in case the app pool is recycled or there's an unhandled exception in the app, but that's another subject).</p>
  
  <p>For that I'm doing something like this:</p>
  
  <pre><code>public ActionResult SendMessages()
  {
    Task.Factory.StartNew(() =&gt; { SendMessagesLongRunningProcess(); });
    return View();
  }
  </code></pre>
  
  <p>inside the long running process I'm trying to render the view for the HTML email and send it. Like this:</p>
  
  <pre><code>private void SendMessagesLongRunningProcess()
  {
    var users = GetUsers();
    foreach (var user in users)
    {
      string message = RenderView("EmailMessage", user);
      SendEmail(user.email, message);
    }
  }
  </code></pre>
  
  <p>Now, I know that my RenderView method works just fine since I use it to render email views in other places. The problem is when I try to execute it in a new thread as I'm doing here.
  This is my RenderView method:</p>
  
  <pre><code>    public string RenderView(string viewName, object model)
      {
          ViewData.Model = model;
          using (var sw = new StringWriter())
          {
              var viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, null);
              var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
              viewResult.View.Render(viewContext, sw);
              return sw.GetStringBuilder().ToString();
          }
      }
  </code></pre>
  
  <p>The error I'm getting is:</p>
  
  <pre><code>Value does not fall within the expected range.
  </code></pre>
  
  <p>When the viewResult.View.Render method is called.</p>
  
  <p>I'm guessing this has to do with the fact that the controller context is no longer valid in the new thread, but I'm not sure.</p>
  
  <p>So, what is the best way to approach this? What alternatives do I have?</p>
  
  <p>Thanks</p>