I am getting a tricky error on an MVC page that only occurs when multiple users are on the site.
The error I get is
Collection was modified; enumeration operation may not execute.
The error occurs on the line that attempts to render a javascript file Bundle.
@Scripts.Render("~/Scripts/js")
The associated code in /app_start -> BundleConfig.cs -> RegisterBundles is pretty standard:
bundles.Add(new ScriptBundle("~/Scripts/js").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-ui-{version}.js",
"~/Scripts/jquery.validate*",
"~/Scripts/jQuery.Buzz/jquery.buzz.js"
));
The error only seems to occur when there are multiple users on the site at once. I managed to reproduce the problem locally by creating multiple tabs in multiple browsers and hitting them as quick as I can.
I've searched and haven't been able to find anyone else with a similar error. The error implies that the a collection is being modified while being looped over. I can't see how the collection of files to be added to the bundle could be changing as the collection is being enumerated.
The Stack trace is as follows:
[InvalidOperationException: Collection was modified; enumeration operation may not execute.]
System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) +56
System.Collections.Generic.Enumerator.MoveNextRare() +14277518
System.Web.Optimization.Bundle.EnumerateFiles(BundleContext context) +266
System.Web.Optimization.Bundle.GenerateBundleResponse(BundleContext context) +38
System.Web.Optimization.Bundle.GetBundleResponse(BundleContext context) +61
System.Web.Optimization.BundleResolver.GetBundleContents(String virtualPath) +214
System.Web.Optimization.AssetManager.DeterminePathsToRender(IEnumerable`1 assets) +410
System.Web.Optimization.AssetManager.RenderExplicit(String tagFormat, String[] paths) +35
ASP._Page_Views_Shared__Layout_cshtml.Execute() in c:\..\Views\Shared\_Layout.cshtml:13
The server was not particularly overloaded at the time the errors occurred. I have monitoring software on the server that showed the CPU and memory at normal levels while the errors were generated.
Any ideas what could be causing this?
UPDATE: After some further searching I discovered that the Bundle was being updated programmatically in the Controller.
BundleTable.Bundles.GetBundleFor("~/Scripts/js").Include("~/Scripts/jquery.mobile-{version}.js");
It turns out this didn't need to be added programmatically so I have included it in the BundleConfig file and the site seems to be behaving now.