Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking / Concurrency Issue

I have the following C# code:

1.    List<BandEdge> bandEdgeList;
2.    
3.    bandEdgeList = CicApplication.BandEdgeCache.Where(row => row.Coater == coater).ToList();
4.    foreach (BandEdge bandEdge in bandEdgeList)
5.       {
6.          ...
7.          ...
8.       }

My question is this. Once 'bandEdgeList' is populated on line 3, if another thread modifies the contents of CicApplication.BandEdgeCache, would the contents of 'bandEdgeList' be invalidated? I have a lock in the CicApplication.BandEdgeCache getter / setter. But I'm wondering if I should put a lock around this block of code so that the contents of CicApplication.BandEdgeCache don't change while I'm working with 'bandEdgeList'.

like image 801
Hosea146 Avatar asked Sep 11 '26 00:09

Hosea146


1 Answers

Not automatically, but this is still not thread-safe. It could throw a InvalidOperationException.

Once ToList is called, its saves a copy of those references. But if another thread modifies BandEdgeCache while that is happening, bad things happen.

So, you should lock all references to BandEdgeCache.

But along the lines of the saved list, that would be safe, but modifying any BandEdge isn't thread-safe without some locking.

like image 189
Daniel A. White Avatar answered Sep 12 '26 13:09

Daniel A. White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!