Let's suppose I have the following piece of code:
IEnumerable<string> allKeys = _cache.Select(o => o.Key);
Parallel.ForEach(allKeys, key => _cache.Remove(key));
As you can see, I'm retrieving all the keys in _cache
, storing them in my local variable allKeys
, and then concurrently removing all the keys from _cache
.
I would like however, to do it one single line. So what comes to mind is:
Parallel.ForEach(_cache.Select(o => o.Key), key => _cache.Remove(key));
But the statement _cache.Select(o => o.Key)
would be called on each loop iteration, therefore retrieving different amount of elements each time (because I'm deleting them at the same time).
Is the latter line of code safe?
Does _cache.Select(o => o.Key)
in loop statements, only get called once, and then each iteration uses the original result, or is it processed in every iteration step?