Suppose I have the following code snippet:
IEnumerable<string> allKeys = _cache.Select(o => o.Key); Parallel.ForEach(allKeys, key => _cache.Remove(key));
As you can see, I am extracting all the keys in _cache , storing them in the local variable allKeys , and then simultaneously deleting all the keys from _cache .
I would like, however, to do this in one separate line. So what comes to mind:
Parallel.ForEach(_cache.Select(o => o.Key), key => _cache.Remove(key));
But the statement _cache.Select(o => o.Key) will be called at each iteration of the loop, so it will extract a different number of elements each time (because I delete them at the same time).
Is the last line of code safe?
Is _cache.Select(o => o.Key) in loop statements, called only once, and then each iteration uses the original result or is processed at each stage of the iteration?
source share