views:

80

answers:

2

Just to make sure, say that i have this code:

this.allObjects =  [some linq query];

and have two methods that both read (not modify) this IEnumerable, are they safe to call in parallel? Just looping through a IEnumerable should be safe right?

A: 

It depends on the implementation of the Enumerator, but in most cases, yes, it is safe.

One note though: the pseudocode, as you have it, doesn't actually do anything (due to deferred execution). The LINQ query will only execute when you access allObjects (or if you call something like ToList() on the LINQ query).

Nader Shirazie
Yes, but that's good right? When I access the linq query by for-eaching over it for instance it will run GetEnumerator and generate a new IEnumerable... looping over the same IEunumerable might be worse..
MattiasK
Correct. The only time concurrency is an issue is if iterating through makes modifications (which is not what anyone would expect, but is possible) -- however this never happens with standard collections.
Nader Shirazie
A: 

The IEnumerable<T> instances are probably fine (although it does depend on implementation).

IEnumerator<T> instances are probably not fine (although again: implementation details).

David B