Creating GetEnumerator ThreadSafe

Exactly how counters work - I know that they build a state machine behind the scenes, but if I call GetEnumerator twice, will I get two different objects?

If I do something like this

  public IEnumerator<T> GetEnumerator()
  {
     yield return 1;
     yield return 2;
  }

Is it possible to use a lock at the beginning of the method and does this lock hold until the counter returns null or until the counter is GC'd?

What happens if the caller resets the counter, etc. -

I think my question is the best way to manage lock when working with an enumerator

Note. The client cannot be held responsible for synchronizing threads. Inner class must be

And finally, the example above is a simplification of the problem. The yield statements do a bit more than I showed :)

+3
source share
2

, GetEnumerator() ( ).

, , , MoveNext() .

, , . , MoveNext(). - , , , .

, , . , , :

public void DoSomething(Action<T> action)
{
    lock (...)
    {
        // Call action on each element in here
    }
}
+8

, . Google : http://www.codeproject.com/KB/cs/safe_enumerable.aspx

IEnumerable , .

- , . , , .

, , , , , . , .

, , . , , , , , . , , , , . , , , .

+2

All Articles