Restart method with fresh list to iterate through without triggering 'collection was modified' error
I've provided a pseudo code version of the problem. This normally wouldn't be a problem as I could just remove the code that modifies the list, however I want this operation to work automatically without my input / manual intervention. What can I add to this code to make that happen? I considered adding cancellation tokens but that would only cancel the current task, it wouldn't take the program out of the current iteration (inside this try catch block).
5 Replies
If you're not using
item
inside the loop, then what is point of the loop being a foreach in the first place?I am using item inside the loop. I didn't include the exact logic for simplicity's sake, but that item is being stored in the db if it meets certain criteria. So it is being used.
I won't even ask why you're mutating a list you're passing into the method
So, normally the task just ends on its own and I then need to manually restart the process with a fresh list. I'm trying to automate that process under certain exceptions. That's why.
SOLVED: I needed to create a new list scoped to that try-catch block and pass the current lists' contents to that new one, then iterate through that one. Simple.
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.