Reputation: 133
I am trying to write the data to a file, and the data is continuously updated every 100ms. So when I click save button then
System.InvalidOperationException: Collection was modified enumeration operation may not execute.
error comes up. Upon my search there is solutions to this probelm if there is Foreach
loop but in my case there is no Foreach
loop.
Bellow is the code I used
File.WriteAllLines(fileDialog.FileName,
RawDataFromSerialPort.Select((v, i) => $"{i + 1} Raw data is -->, {v.ToString()}"));
Upvotes: 0
Views: 323
Reputation: 133
The problem was that the List name I was accessing was wrong so correcting the list name RawDataFromSerialPort
made my problem solved
Upvotes: 0
Reputation: 83
Check the stacktrace as well, there you'll find the drill down of the call stack where eventually a foreach-(like)loop is used.
Click on the 'view details' link, expand the $exception node and look for the StackTrace field.
Upvotes: 1
Reputation: 80
I'd say your serial port is still receiving data on a background thread whilst you're trying to read from the raw data collection, I'd suggest making a copy of the collection and then writing the copy out to the file.
Try using the syncroot property on the collection while doing the copy.
https://learn.microsoft.com/en-us/dotnet/api/system.array.syncroot?view=netframework-4.7.2
Upvotes: 1