multithreading - Parallel.For w Action that creates different tasks, c# -
i want in parallel load list tasks, , in parallel execute tasks. tasks take method action, need method work on different objects every task. couldn't pass in parameters.
so i'm thinking of solution this:
public static order order = new order(); public static queue<suborder> subsq = order.suborders; public void work() { task[] tasklist = taskmaker(order.suborders.count); task.waitall(tasklist); } public task[] taskmaker(int ordercount) { task[] tasklist = new task[order.suborders.count]; parallel.for(0, tasklist.length, => tasklist[i] = new task(executesuborder) ); return tasklist; } public void executesuborder() { suborder subo = subsq.dequeue(); // ... execute suborder, webrequest etc. orderscompletedtable.execute(tableoperation.insert(new suborder(subo.suborderid, subo.status)), new tablerequestoptions() { retrypolicy = new linearretry(timespan.fromseconds(3), 3) }); } public class order { public queue<suborder> suborders { get; set; } }
the method executes order, , upon every completed order, records in azure table. method dequeues new order every task put task[] parallel.for, can call parallel.waitall task-array.
can done so, or should differently? getting job done in parallel here?
you're using parallel.for
create new task each suborder, retrieving suborders shared data structure within tasks. not ideal route, since lead race hazard (if unsynchronized) or bottleneck (if synchronized) when each task starts executing.
instead, alter definition of executesuborder
method accept suborder parameter, use parallel.foreach
parallelize suborders onto tasks. parallel.foreach
takes care of waiting suborders complete before returning.
public void work() { parallel.foreach(order.suborders, executesuborder); } public void executesuborder(suborder subo) { // ... execute suborder, webrequest etc. orderscompletedtable.execute(tableoperation.insert(new suborder(subo.suborderid, subo.status)), new tablerequestoptions() { retrypolicy = new linearretry(timespan.fromseconds(3), 3) }); }
Comments
Post a Comment