Parallel.Foreach + yield return?

Short version – no, that isn’t possible via an iterator block; the longer version probably involves synchronized queue/dequeue between the caller’s iterator thread (doing the dequeue) and the parallel workers (doing the enqueue); but as a side note – logs are usually IO-bound, and parallelising things that are IO-bound often doesn’t work very well. If … Read more

Using IEnumerable without foreach loop

You can get a reference to the Enumerator, using the GetEnumerator method, then you can use the MoveNext() method to move on, and use the Current property to access your elements: var enumerator = getInt().GetEnumerator(); while(enumerator.MoveNext()) { int n = enumerator.Current; Console.WriteLine(n); }

yield return statement inside a using() { } block Disposes before executing

When you call GetAllAnimals it doesn’t actually execute any code until you enumerate the returned IEnumerable in a foreach loop. The dataContext is being disposed as soon as the wrapper method returns, before you enumerate the IEnumerable. The simplest solution would be to make the wrapper method an iterator as well, like this: public static … Read more

What is the purpose/advantage of using yield return iterators in C#?

But what if you were building a collection yourself? In general, iterators can be used to lazily generate a sequence of objects. For example Enumerable.Range method does not have any kind of collection internally. It just generates the next number on demand. There are many uses to this lazy sequence generation using a state machine. … Read more

tech