Let's say that I have the following sample code:
private static async Task Main(string[] args)
{
var result = Enumerable.Range(0, 3).Select(x => TestMethod(x)).ToArray();
Console.ReadKey();
}
private static int TestMethod(int param)
{
Console.WriteLine($"{param} before");
Thread.Sleep(50);
Console.WriteLine($"{param} after");
return param;
}
The TestMethod will run to completion 3 times, so I'll see 3 pairs of before
and after
:
0 before
0 after
1 before
1 after
2 before
2 after
Now, I need to make TestMethod asynchronous:
private static async Task<int> TestMethod(int param)
{
Console.WriteLine($"{param} before");
await Task.Delay(50);
Console.WriteLine($"{param} after");
return param;
}
How can I write a similar Select expression for this async method? If I just use an async lambda Enumerable.Range(0, 3).Select(async x => await TestMethod(x)).ToArray();
, that won't work because it won't wait for completion, so before
parts will be called first:
0 before
1 before
2 before
2 after
0 after
1 after
Note that I don't want to run all 3 calls in parallel - I need them to execute one by one, starting the next one only when the previous one has fully finished and returned the value.