Suppose I have an IEnumerable such as a List(TValue) and I want to keep track of whether this list is being accessed (to prevent issues with, say, adding to the list while it is being iterated over on a different thread); I can always write code such as the following:
Dim List1 As New List(Of Integer)
Dim IteratingList1 As Boolean = False
' ... some code ... '
Private Function getSumOfPositivesFromList1() As Integer
If IteratingList1 Then Return -1
IteratingList1 = True
Dim SumOfPositives As Integer = 0
For Each x As Integer In List1
If x > 0 Then SumOfPositives += x
Next
IteratingList1 = False
Return SumOfPositives
End Function
(I realize this code is very arbitrary, but it illustrates what I'm talking about.)
My question is whether there's a better/cleaner way to perform this check than by manually updating and accessing a Boolean, as above. I feel like there must be, but, to my knowledge, there isn't any IEnumerable class with a built-in "I am being iterated over" method or property. And writing a new class that implements IEnumerable and contains such a property seems like overkill to me.