Avatar ·

C#中WCF操作字典时出现“Collection was modified; enumeration operation may not execute”错误

大家好!我正在编写一个WCF服务,同时处理多个客户端的请求。在服务内部,我使用静态字典`Dictionary`来缓存数据。当客户端发送请求时,我有时会更新这个字典(添加/删除元素),同时通过`foreach`循环读取它。突然遇到异常:“Collection was modified; enumeration operation may not execute”。 以下是简化代码: ```csharp public class MyService : IMyService { private static Dictionary _cache = new Dictionary(); public string GetData(int key) { // 有时会向字典添加内容 if (!_cache.ContainsKey(key)) { _cache.Add(key, FetchFromDatabase(key)); } // 在其他地方,例如后台缓存清理方法中 // foreach (var item in _cache) { ... } — 这里就会抛出异常 return _cache[key]; } private void CleanCach