We are using .NET Core 3.1 with MVC architecture. We have a simple view (Index.cshtml
file) which renders a list of in-memory items returned from the singleton service. This is why we need locking mechanism - one thread can add items to the list while they are still being looped over with foreach
in Index.cshtml
. If this occurs, the exception Collection was modified; enumeration operation may not execute
is thrown.
Index.cshtml
@{
var lockObj = new object();
var collection = Enumerable.Range(1, 10); // returned from the singleton service
}
@lock (lockObj)
{
@foreach (var item in collection)
{
<a asp-controller="Home" asp-action="Index" asp-route-id="@item">
@item
</a>
}
}
I am aware that code above doesn't make any sense (lockObj
needs to be shared among all application layers, it shouldn't be initialized in the view), but it clearly reproduces the build error that I get. Once I build the solution, compiler throws the following error:
CS1996 Cannot await in the body of a lock statement
If I remove asp-*
tag helpers, the code compiles successfully. What am I doing wrong? Do asp-*
tag helpers use async
methods under the hood? Can I use asp-*
tag helpers inside lock
statement?