c# - Why do async await without being told -
i trying make part of system run in parallel, some reason wait each element before starts next though have not told await. start executing executeitem each this.items , continue when done.
bool singlethread = false; public async task execute() { if (!this.singlethread) { var tasks = this.items.select(x => this.executeitem(x)).toarray(); task.waitall(tasks); } else { foreach (var item in this.items) { await this.executeitem(item); } } } private async task executeitem(imyitem item) { mappeddiagnosticscontext.set("itemref", item.itemref); try { await this.handelitem(item); } catch (exception exp) { logger.errorexception(string.format("execution {0} failed.", item.itemname), exp); logger.error("error message: ", exp.message); } mappeddiagnosticscontext.remove("itemref"); } to make clear problem code behaves if had wrote following
var tasks = this.items.select(x => await this.executeitem(x)).toarray(); to make sure not kind of linq problem have rewriten problem code following, code still blocks tasks[i] = this.executeitem(this.items[i]);
task[] tasks = new task[this.items.count]; (int = 0; < this.items.count; i++) { console.writeline("adding " + this.items[i].itemname); tasks[i] = this.executeitem(this.items[i]); } console.writeline("waiting!!!"); task.waitall(tasks);
something in handelitem blocking.
async methods don't run asynchronously, execute synchronously until point hit await. of executeitem, handelitem run before tasks list built. synchronous behavior continue handelitem if async method, handelitem executing while building tasks list.
this seen example program:
static void main(string[] args) { var items = enumerable.range(1, 2); console.writeline("start"); var tasks = items.select(i => asyncmethod(i)).toarray(); console.writeline("got tasks"); task.waitall(tasks); console.writeline("done!"); } static async task asyncmethod(int i) { console.writeline("enter {0}", i); await asyncmethod2(i); await task.delay(1000); console.writeline("exit {0}", i); } static async task asyncmethod2(int i) { console.writeline("enter2 {0}", i); await task.delay(2000); console.writeline("exit2 {0}", i); } it's output is:
start enter 1 enter2 1 enter 2 enter2 2 got tasks exit2 2 exit2 1 exit 1 exit 2 done! so both async methods run while building task list, until point have wait. if handelitem non-asynchronous, cause blocking.
Comments
Post a Comment