Use a concurrent dictionary. Locking is implemented for you. And it is thread safe.
Read IEnumerable or wait for it to finish changing first
-
13-07-2023 - |
Pergunta
I want to read a Dictionary in C# and possibly get a list or dictionary from it using linq. My problem is that the list can change at any point when I make the request (ie not thread safe i guess).
Can someone give me a example of how I can do this? Would I need to use 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;
}
This is the exception im getting:
Additional information: Collection was modified; enumeration operation may not execute. Thanks
Solução
Outras dicas
You can also implement this as an extension method on IDictionary
and then you can pass in whatever dictionary you want concurrent or otherwise
public static class Extensions
{
public static IDictionary<DateTime, T> GetLatest<T>(this IDictionary<DateTime, T> dict, DateTime since)
{
var returnList = new Dictionary<DateTime, T>();
returnList = dict.Where(x => x.Key > since).ToDictionary(x => x.Key, x => x.Value);
return returnList;
}
}
And you use it like this:
dict.GetLatest(new DateTime(2014, 1, 1));
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow