c# - LINQ on loop conditions -
let's suppose have following piece of code:
ienumerable<string> allkeys = _cache.select(o => o.key); parallel.foreach(allkeys, key => _cache.remove(key));
as can see, i'm retrieving keys in _cache
, storing them in local variable allkeys
, , concurrently removing keys _cache
.
i however, 1 single line. comes mind is:
parallel.foreach(_cache.select(o => o.key), key => _cache.remove(key));
but statement _cache.select(o => o.key)
called on each loop iteration, therefore retrieving different amount of elements each time (because i'm deleting them @ same time).
is latter line of code safe?
does _cache.select(o => o.key)
in loop statements, called once, , each iteration uses original result, or processed in every iteration step?
as can see, i'm retrieving keys in _cache, storing them in local variable allkeys
no, don't. due called deferred execution, store command keys. need materialize command think do:
var allkeys = _cache.select(o => o.key).tolist();
that said: cache thread safe? why not feature clear method? getting keys , removing using multi threading seems not-so-great-idea.
if insist have in 1 line, use plinq:
_cache.select(o => o.key).asparallel().forall(key => _cache.remove(key));
but again: seems bad idea.
Comments
Post a Comment