A debate formed about a lock statement in our team – I would appreciate some external feedback about this. The questionable code part is:
lock (IndexLock)
{
currentIndex = Index;
}
You can see part of the class below:
public class BuilderService
{
private ImmutableList<Model> Index { get; set; } = ImmutableList<Model>.Empty;
private object IndexLock { get; } = new();
public Add(Model item)
{
lock (IndexLock)
{
Index = Index.Add(item);
}
}
public void GetFilterLinesExcluding()
{
var filters = new List<Model>();
ImmutableList<FilterModel> currentIndex;
lock (IndexLock)
{
currentIndex = Index;
}
foreach (var filter in currentIndex)
{
...
}
Without going into the details, the debate is around phenomenons like:
- memory visibility
- memory barriers
- stale values
Does it make sense to have a lock around currentIndex = Index
?
I will provide more information if required.
Thank you in advance!