3 ms·
The one I am concerned about is iterators (for each). I have read somewhere that iterators are stateful and I should be careful when using them in a multi-threa
by cm2187 10y ago
The one I am concerned about is iterators (for each). I have read somewhere that iterators are stateful and I should be careful when using them in a multi-threaded environment. Currently I am ignoring this advice and use them happily (on static lists and dictionaries) but I am not sure if this isn't going to bite me some day. But I don't understand how it would bite me.
- jdmichal 10y agoThat is because your different threads are not using the same `Enumerator`. I'm guessing your threads look something like this, based on your mention of `foreach`: // In multiple threads: foreach(element in collection) { ... } `collection` is not an `Enumerator` but rather an `Enumerable`. The `foreach` statement calls `collection.GetEnumerator`, so each thread gets its own iterator. You would only see inconsistencies if another thread modified the collection during iteration. Try this instead, and you'll guaranteed see issues: // Before: IEnumerator enumerator = collection.getEnumerator(); // In multiple threads: while(enumerator.Move()) { var element = enumerator.Current; }