Csantucci, on 08 February 2015 - 11:53 PM, said:
I would like to have this clarified better: you say:
"Nobody modifies the value in-place (as in, adding items to the List) - everybody must modify the value in a copy and replace the whole value in a single assignment (which is atomic)."
Referring to a list this would mean for the process modifying the list:
- make a local copy of the list (which is atomic, while generating an array from the list is not atomic)
- modify the local copy
- copy back the local copy to the original copy; (which is again atomic)
while for the process accessing the above list to operate on it it would mean
- make a local copy of the list (atomic operation)
- work on the local copy.
Did I understand correctly?
"Nobody modifies the value in-place (as in, adding items to the List) - everybody must modify the value in a copy and replace the whole value in a single assignment (which is atomic)."
Referring to a list this would mean for the process modifying the list:
- make a local copy of the list (which is atomic, while generating an array from the list is not atomic)
- modify the local copy
- copy back the local copy to the original copy; (which is again atomic)
while for the process accessing the above list to operate on it it would mean
- make a local copy of the list (atomic operation)
- work on the local copy.
Did I understand correctly?
Pretty close, but you need to differentiate reading the field and creating a new List from the existing one when using "atomic".
Reading and writing the value from the field is atomic. It's just reading and writing a pointer, which is guaranteed to be atomic. Pretty much everything else is not guaranteed to be atomic. Calling any methods/constructors, such as making a copy of the list with "new List", just like turning it in to an array with "ToArray", is not atomic.
The reason that doing "SharedField.ToArray()" is probably fine is that it is implicitly reading the shared field just once, to call a method on it.
The key things to remember are:
- Never modify an object in a shared field - once you've assigned a List to the field, you must never change that List again, it can only be replaced with a new List.
- Only read the field once in each place that uses it - otherwise you may get different Lists if the field has been replaced while the code was running. (If you're doing a for (var i loop this is especially important.)