Proper async looping in console app

Proper async looping in console app



I know async I/O doesn't bring parallelism but I thought when the app is awaiting an async operation it could carry on doing other stuff.



Consider the below code I would expect the loop to carry on while awaiting Wait(i) but obviously I was wrong and each iteration is blocking. What's the correct way to achieve some concurrency here?


using System;
using System.Threading.Tasks;

namespace asynctest

class Program

static void Main(string args)

Do().GetAwaiter().GetResult();


public static async Task Do()

for(int i=0;i<10;i++)

await Wait(i);



public static async Task Wait(int i)

await Task.Delay(10000);







This is what await do. It suspends the loop to make your concurrent code run sequentially.
– Maxim Kosov
Aug 27 at 7:27


await





await generally blocks operation to wait for other operation to complete. But here it seems blocking every iteration because each iteration is taking almost the same amount of time. You could have understand the difference if you would put different type of tasks in a Task array and process the array index with await operator
– Rashedul.Rubel
Aug 27 at 7:42





2 Answers
2


public static async Task Do()

var tasks = new Task[10];
for (int i = 0; i < 10; i++)

tasks[i] = Wait(i);


await Task.WhenAll(tasks);



You should use WhenAll() to combine the task results, thus your tasks will run in parallel:


WhenAll()


namespace asynctest

class Program

static void Main(string args)

Do().GetAwaiter().GetResult();


public static async Task Do()

for(int i=0;i<10;i++)


var task1 = Wait(5000);
var task2 = Wait(3000);
int result = await Task.WhenAll(task1, task2);
Console.WriteLine("waited for a total of " + result.Sum() + " ms");



public static async Task<int> Wait(int i)

await Task.Delay(i);
return i;








By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)