c# - Trouble with AWAIT / ASYNC and WebApi with FOREACH -
i have multiple async
methods return same type different oauth based rest api calls.
if call 1 directly, can data back:
//call specific provider public async task<list<contacts>> get() { return await providers.specificprovider.getcontacts(); }
however, if try loop through multiple accounts, object returning before await
finishes:
//call providers public async task<list<contacts>> get() { return await providers.getcontactsfromallproviders(); } public async task<list<contacts>> getcontactsfromallproviders() { var returnlist = new list<contacts>(); //providers inherits list<>, can enumerated trigger //all objects in collection foreach (var provider in providers) { var con = await provider.getcontacts(); returnlist.add(con); } return returnlist; }
i'm new async
, missing simple
the code have provided call web service each provider 1 one in serial fashion. not see how statement the object returning before await finishes can true because inside loop call getcontacts
awaited.
however, instead of calling providers serially can call them in parallel in cases should decrease execution time:
var tasks = providers.select(provider => provider.getcontacts()); // tasks execute in parallel - wait them complete. var result = await task.whenall(tasks); // combine returned lists single list. var returnlist = result.selectmany(contacts => contacts).tolist();
Comments
Post a Comment