c# - Transform IEnumerable<Task<T>> asynchronously by awaiting each task -


today wondering how transform list of tasks awaiting each of it. consider following example:

private static void main(string[] args) {     try     {         run(args);                         console.readline();     }     catch (exception ex)     {         console.writeline(ex.tostring());         console.readline();     } }  static async task run(string[] args) {     //version 1: compile, ugly , list<t> overhead     var tasks1 = gettasks();                             list<string> gainstrings1 = new list<string>();     foreach (task<string> task in tasks1)     {         gainstrings1.add(await task);     }     console.writeline(string.join("", gainstrings1));      //version 2: not compile     var tasks2 = gettasks();     ienumerable<string> gainstrings2 = tasks2.select(async t => await t);     console.writeline(string.join("", gainstrings2)); }  static ienumerable<task<string>> gettasks() {     string[] messages = new[] { "hello", " ", "async", " ", "world" };      (int = 0; < messages.length; i++)     {         taskcompletionsource<string> tcs = new taskcompletionsource<string>();         tcs.setresult(messages[i]);         yield return tcs.task;     } } 

i'd transform list of tasks without foreach, either anonymous function syntax nor usual function syntax allows me foreach does.

do have rely on foreach , list<t> or there way work ienumerable<t> , advantages?

what this:

await task.whenall(tasks1); var gainstrings = tasks1.select(t => t.result).tolist(); 

wait tasks end , extract results. ideal if don't care in order finished.

edit2: better way:

var gainstrings = await task.whenall(tasks1); 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -