As it is known, if during the work of foreach collection that it iterates will be changed (in another thread, for example), an exception will occur. But how does this mechanism of exceptions work? Who is responsible for detecting the change? Should I, when developing my collections, take any measures to support this behavior, or will everything always start out of the box ?
2 answers
The foreach equivalent to approximately the following code:
int[] a = { 1, 2, 3, 4 }; var enumerator = ((IEnumerable<int>)a).GetEnumerator(); while (enumerator.MoveNext()) { var item = enumerator.Current; // ... тело цикла ... } Thus, it all depends on the implementation of the IEnumerable<T>.GetEnumerator() method in a particular collection.
For most of the collections built into .Net, this method returns a class that keeps track of the private version property of the collections. Which in turn increases by 1 every time the collection changes.
With the exception of one bug, which I have already written to Microsoft, but it did not bother. The List<T>.Sort(Comparison<T> comparison) method does not call a version increment.
- 2with sorting fun. - Grundy
Should I, when developing my collections, take any measures to support this behavior, or will everything always start out of the box?
But it depends on what you have for the collection.
A collection that always returns random elements should definitely not think about it.
A collection that works with a network can easily load data on the go — likewise, I would not fall because of changes in content.
Rely on the substantive logic, and not on the mass behavior.
Enumeratorthat is used - Grundy