我想阅读 C# 中的字典,并可能使用 linq 从中获取列表或字典。我的问题是,当我发出请求时,列表可以随时更改(即我猜不是线程安全的)。
有人可以给我一个例子来说明如何做到这一点吗?我需要使用lock()吗?
public Dictionary<DateTime, decimal> GetLatest(DateTime since, Dictionary<DateTime, decimal> requestedDict)
{
Dictionary<DateTime, decimal> returnList = new Dictionary<DateTime, decimal>();
returnList = requestedDict.Where(x => x.Key > since).ToDictionary(x => x.Key, x => x.Value);
return returnList;
}
这是我遇到的异常:
Additional information: Collection was modified; enumeration operation may not execute. Thanks
最佳答案
使用并发字典。锁定已为您实现。而且它是线程安全的。
关于c# - 先读取 IEnumerable 或等待其完成更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23417658/