Naudio Reader<WaveStream> list crash issue [Race condition]

38 Views Asked by At

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.

1

There are 1 best solutions below

0
Mark Heath On

If a List<T> is modified while you foreach through 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 calling ToArray you 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.