c# - async within a LINQ code - Clarification? -
almost every so's answer regarding topic , states :
also :
but in stephen's book there sample :
problem: have collection of tasks await, , want processing on each task after completes. however, want processing each 1 as as completes, not waiting of other tasks.
one of recommended solutions :
static async task<int> delayandreturnasync(int val) { await task.delay(timespan.fromseconds(val)); return val; } // method prints "1", "2", , "3". static async task processtasksasync() { // create sequence of tasks. task<int> taska = delayandreturnasync(2); task<int> taskb = delayandreturnasync(3); task<int> taskc = delayandreturnasync(1); var tasks = new[] { taska, taskb, taskc }; var processingtasks = tasks.select(async t => { var result = await t; trace.writeline(result); }).toarray(); // await processing complete await task.whenall(processingtasks); }
question #1:
i don't understand why async
inside linq statement - work . didn't "don't think using async
within linq" ?
question #2:
when control reaches await t
here — happen? control leaves processtasksasync
method ? or leaves anonymous method , continue iteration ?
i don't understand why async inside linq statement - work . didn't "don't think using async within linq" ?
async
mostly doesn't work linq because ienumerable<t>
extensions don't infer delegate type , defer action<t>
. have no special understanding of task
class. means actual async delegate becomes async void
, bad. in case of enumerable.select
, have overload returns func<t>
(which in turn func<task>
in our case), equivalent async task
, hence works fine async use-cases.
when control reaches await t here — happen? control leaves processtasksasync method ?
no, doesn't. enumerable.select
projecting elements in sequence. means each element in collection, await t
yield control iterator, continue iterating elements. that's why later have await task.whenall
, ensure elements have finished execution.
Comments
Post a Comment