Avatar ·

Error "Collection was modified; enumeration operation may not execute" in C#: how to fix?

Hello colleagues! I'm a beginner in C# and WCF, and I encountered a strange error: "Collection was modified; enumeration operation may not execute". \n\nI have a WCF service that processes orders. Inside the service, I use `ConcurrentDictionary` to store active orders. Periodically, I run a background thread that checks order statuses and removes completed ones. Here's simplified code:\n\n```csharp\npublic class OrderService\n{\n private ConcurrentDictionary _orders = new ConcurrentDictionary();\n\n public void ProcessOrders()\n {\n // Background thread for cleanup\n Task.Run(() =>\n {\n while (true)\n {\n foreach (var kvp in _orders)\n {\n if (kvp.Value.