c# - .net Parallel and Serial looping -


we build pattern around loops in our solution, allow them run in serial, or parallel, depending on factors. below general form of it.

since concurrent collections dont share common interface regular collections, need sort of adapter write general code.

specifically around usage of addfunc delegate in loop body, there there end causing problems in long term might miss? runs fine of now, but....?

action<sometype> addfunc;  if(runinparallel) {    addfunc = concurrentbag.add;    loopdelegate = parallel.foreach; } else {    addfunc = ilist.add;    loopdelegate = serial.foreach; // wrapper delegate foreach }  loopdelegate(source, item => {    sometype result = longrunningtask(item);    ...    addfunc(result); //  }); 

curious why not use tpl in .net 4.0? http://msdn.microsoft.com/en-us/library/dd537609.aspx

there excellent white paper of considerations have taken when developing tpl, if can't use .net 4, should @ paper , consider of gotcha's in there.

updated based on comment pointing out obvious.

i'd use syntactic sugar like,

foreach<tsource>(predicate<ienumerable<tsource>> isparallel, ienumerable<tsource> source, action<tsource> body) {     if(isparallel(source))     {         parallel.foreach<tsource>(source, body);     }     else     {         foreach (tsource element in source)         {             body(element);         }     } } 

there 2 main advantages on implementation.

  1. you enumerate twice, once add items loop over, , 2nd time during execution.
  2. it not obvious, you're stopping parallel.foreach, , foreach using efficient getter. parallel.foreeach not use getenumerator in ienumerable. enumerator design not concurrent, if item implements ilist, parallel.foreach use indexer allow each thread access element in source without waiting on enumerator iterate through list. concurrentbag not implement ilist.

this paper referring btw, http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=19222.

it's read if you're imeplemeting this, pay particular attention to, pages 1[5-7], 26, 3[0-2].

the syntactic sugar means can call tpl,

myparllellibrary.foreach( (list) => true, list), item => {     // code }); 

Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -