c# - Parallel.Foreach vs Foreach and Task in local variable -
when use foreach , tasks need use local variables this:
list<task> taskpool = new list<task>(); foreach (targettype item in source) { targettype localitem = item; taskpool.add(task.factory.startnew(() => dosomething(localitem))); } task.waitall(taskpool.toarray()); but how parallel.foreach, use this:
parallel.foreach(source, (targettype item) => dosomething(item)); so there not local variable see. how parallel.foreach work? there no need introduce local variables? or if needed, how can define it?
update
is there difference in .net 4 , .net 4.5?
you not define local variable in parallel.foreach - item nothing more formal parameter - implementation code of parallel.foreach 1 have handle variables, , whether local, captured or else.
there no need define local variable related formal parameter parallel.foreach - caller code of anonymous delegate handle variable , pass function.
however in c#4, might need use local variable if capture variable, is:
void dosomething(itemtype item, othertype other) { } void yourfunction(ienumerable<itemtype> items, ienumerable<othertype> others) { foreach (var otheritem in others) { var localotheritem = otheritem; parallel.foreach(items, item => dosomething(item, localotheritem)); } } you can see difference above: localotheritem taken context anonymous function defined: called closure. whereas items in items passed method parameter anonymous function.
in short: item in parallel.foreach , item in c# foreach 2 different problems.
Comments
Post a Comment