.net - Running multiple Task -
i'm trying execute multiple tasks @ same time
private static void main(string[] args) { while (true) { console.foregroundcolor = consolecolor.white; console.write("enter number of cart: "); var numofcarts = convert.toint32(console.readline()); console.write("enter number of items: "); var numofitems = convert.toint32(console.readline()); runtasks(numofcarts, numofitems).wait(); } } public static async task runtasks(int numofcarts, int numofitems) { (var = 0; < numofcarts; i++) await task.run(() => { var color = (consolecolor) new random().next(0, 15); (var q = 0; q < numofitems; q++) { console.foregroundcolor = color; console.writeline("cart {0} : {1}", i, q); } }); }
is correct implementation? foregroundcolor changes. console color different each cart.
do not mix task.wait()
calls , async / await
. in case, may lead deadlock when main thread waits runtasks
execute while runtasks
waits main thread start continuation.
in case, use task.whenall
:
private static void main(string[] args) { while (true) { console.foregroundcolor = consolecolor.white; console.write("enter number of cart: "); var numofcarts = convert.toint32(console.readline()); console.write("enter number of items: "); var numofitems = convert.toint32(console.readline()); runtasks(numofcarts, numofitems).wait(); } } public static task runtasks(int numofcarts, int numofitems) { task[] tasks = new task[numofcarts]; (var = 0; < numofcarts; i++) { tasks[i] = task.run(() => { var color = (consolecolor) new random().next(0, 15); (var q = 0; q < numofitems; q++) { console.foregroundcolor = color; console.writeline("cart {0} : {1}", i, q); } }); } return task.whenall(tasks); }
runtasks
starts manytask
s , returns task complete when subtasks complete.main
startruntasks
, block main thread untilruntasks
finishes.
at same time, can make await task.whenall
in runtasks
, await runtasks()
in main
, doesn't make sense - main thread busy , infinitely 1 job (which runtasks
).
Comments
Post a Comment