Search code examples
c#collectionsiterationconcurrent-collections

Are there good IList and IDictionary implementations in C# that support fail-safe iteration?


Per the title - are there good built-in options in C#/.NET for fail-safe iteration over an IList or an IDictionary?

Where I'm running into problems is with code similar to the following:

IList<Foo> someList = new List<Foo>();

//...

foreach (Foo foo in someList) {
  if (foo.Bar) {
    someList.remove(foo);
  }
}

which throws the following after the first time foo.Bar is true:

Type: System.InvalidOperationException
Message: Collection was modified; enumeration operation may not execute.

I know the easy workaround is to do foreach (Foo foo in new List<Foo>(someList)), but it's annoying to have to remember to do that every. single. time. this comes up.

Coming from a Java background, that's something that can be handled neatly with a CopyOnWriteArrayList/ConcurrentHashMap (I'm aware that there are other penalties associated with using those lists.) Is there an equivalent in C# that I'm just not aware of?


Solution

  • If you're using .NET 4, there's ConcurrentDictionary<TKey, TValue> and ConcurrentBag<T> (and a queue and a stack in the same namespace). There's nothing which implements IList<T> as far as I'm aware though.