Avatar ·

Error "Collection was modified; enumeration operation may not execute" in C# when working with a dictionary in WCF

Hello, colleagues! I'm writing a WCF service that processes requests from multiple clients simultaneously. Inside the service, I use a static `Dictionary` for caching data. When clients send requests, I sometimes update this dictionary (add/remove elements) and simultaneously read it in a `foreach` loop. Suddenly I get an exception: "Collection was modified; enumeration operation may not execute". \n\nHere's simplified code:\n\n```csharp\npublic class MyService : IMyService\n{\n private static Dictionary _cache = new Dictionary();\n\n public string GetData(int key)\n {\n // Sometimes adding to the dictionary\n if (!_cache.ContainsKey(key))\n {\n _cache.Add(key, FetchFromDatabase(key));\n }\n```