I have a Webstream reader<WaveStream> list and I am disposing WaveStream using foreach loop as mention below
foreach (WaveStream ws in readers)
ws.Dispose();
but reader<WaveStream> list is modified by another method at the same time when foreach loop disposing the object
hence we got unhandled exception collection was modified by another method and our application crashed
could you please provide some explanation or explanation link how our crash issue resolved after using for loop as mentioned below?
for (int i = 0; i <= readers.ToArray().Length - 1; i++)
{
readers[i].Dispose();
}
I am not able to understand how for loop and readers.ToArray() resolved the crash issue.
If a
List<T>is modified while youforeachthrough it, you will get an exception, as the underlying collection has changed. So in your case either another thread was changing the list while you iterated through it, or the very action of Disposing streams was modifying the list. By callingToArrayyou create a new array which is a copy of the original list. No one else has access to that array so its contents will not change while you iterate through it.