c# - sequential execution inside a parallel for each loop -
my requirement thing this. have few independent jobs , few sequential jobs abide contract. in client app, inside parallel loop need make sure independent tasks executed in order if sequential should 1 after another. below code. thanks,
using system; using system.collections.generic; using system.linq; using system.text; using system.reflection; using system.threading.tasks; namespace sample { class program { static void main(string[] args) { program p = new program(); list<icontract> list = p.run(); parallel.foreach(list, t=> t.execute()); } list<icontract> run() { list<icontract> list = new list<icontract>(); type[] typesinthisassembly = assembly.getexecutingassembly().gettypes(); array.foreach( typesinthisassembly, type => { // if type of interface not ichartview, continue loop if (type.getinterface(typeof(icontract).tostring()) != null) { var contractobj = activator.createinstance(type, new object[] { }) icontract; list.add(contractobj); } }); return list; } } public interface icontract { void execute(); } public class xmljob : icontract { public void execute() { console.writeline("step1: getting data xml"); } } public class dumptodbjob : icontract { public void execute() { console.writeline("step2: dumping data whihc came in xml"); } } public class independentjob1 : icontract { public void execute() { console.writeline("this independent job"); } } public class independentjob2 : icontract { public void execute() { console.writeline("this independent job "); } } }
desire out put
this independent job step1: getting data xml step2: dumping data whihc came in xml independent job press key continue . . .
can this
program p = new program(); list<icontract> list = p.run(); icontract xj = list.find(i => i.gettype().tostring() == typeof(xmljob).tostring()); icontract dj = list.find(i => i.gettype().tostring() == typeof(dumptodbjob).tostring()); list.remove(xj); list.remove(dj); parallel.foreach(list, l => l.execute()); list<task> tasks = new list<task>(); task t1 = task.factory.startnew(xj.execute); task t2 = t1.continuewith((antecedent)=>dj.execute()); tasks.add(t1); tasks.add(t2); task.waitall(tasks.toarray());
for of sequential tasks should have single icontract
. execute method of contract should call 2, 3, etc. methods need run sequentially. if have group of 2 tasks run sequentially icontract
. should not have more 1 icontract
s defined group of tasks should run in sequence. if don't want way you'll need re-design entire framework introduce dependencies or more involved.
Comments
Post a Comment