简体   繁体   中英

Prevent collection from being modified while enumerating

how do i prevent Collection from being modified during Enumeration.

Here is the class source code.

 public class cars : IEnumerator,IEnumerable
 {
  private car[] carlist;
  int position = -1;

  public IEnumerator GetEnumerator()
  { return (IEnumerator)this; }

  public bool MoveNext()
  {
     position++;
     return (position < carlist.Length);
  }

  public void Reset()
  {position = 0;}

  //IEnumerable
  public object Current
  { get { return carlist[position];}
  }
 }      

Firstly, your collection class should not implement IEnumerator – it should implement IEnumerable only and return an instance of another class that implements IEnumerator (possibly carEnumerator ) when GetEnumerator() is called.

IEnumerator (implemented in carEnumerator ) extends IDisposable so, in cars.GetEnumerator() , you can set a private flag (perhaps private bool isEnumerating ) to true. In carEnumerator , keep a reference to the collection (cars) and, in carEnumerator.Dispose() , set isEnumerating back to false.

Finally, in all the methods in cars that you want to disable while enumeration is ongoing, check the state of isEnumerating and throw an exception or do nothing if it is true.

At least some of the BCL collections do this by including a version counter. Each modification of the collection increments the counter. When an enumeration of the collection is started the current value of the version count is kept. On each call to the enumerator's MoveNext the underlying collection's version is checked against the kept counter, if different an exception is thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM