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

.name

Greenpeace

Thomas Howard, 21st Earl of Arundel