I’m currently running a simple peace of code that renders a partial view and adds the result to a ConcurrentBag:
Threading.Tasks.Parallel.For(0, Model.Count,
Sub(i)
carXmls.Add(Html.Partial("PublisherVehicleXml16", Model(i)))
End Sub)
The sad thing is that every once in a while this thing crashes with the following exception: Stack empty.
This happens intermittently and only on our staging and production environments. Any ideas where this might be coming from?
Edit: carsXmls is declared like this:
Dim carXmls As New Collections.Concurrent.ConcurrentBag(Of MvcHtmlString)
and the full exception is:
Message Stack empty.
Source System
Target site T Pop()
Stack trace
at System.Collections.Generic.Stack1.Pop() at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() at1 continuation) at
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() at
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
pageContext, TextWriter writer, WebPageRenderingBase startPage) at
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.b__19()
at
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext
controllerContext, IList`1 filters, ActionResult actionResult) at
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName)
You are running code on multiple threads which is using ASP.NET objects. ASP.NET (MVC) does not guarantee you that this is safe. And as you can see, it is unsafe.
In short, you cannot use the ASP.NET infrastructure concurrently.
I suggest that you extract all heavy computations so that you can paralleled them without using ASP.NET objects. You can then render the views sequentially.