I have the following code in LINQPad:
async Task Main()
{
await PrintLoop(Print1());
}
async Task Print1()
{
Debug.WriteLine("Printing!");
}
//Print 2
//Print 3
//etc.
async Task PrintLoop(Task printer, int iterations = 3)
{
for (int i = 0; i < iterations; i++)
{
await printer;
}
}
I can't for the life of me figure out why I get the following output:
Printing!
As opposed to "Printing!" x3.
If I call Print1() directly within the loop I get the following output:
Printing!
Printing!
Printing!
Printing!
Which kind of makes sense but isn't what I want to do. Instead, I would like for Print1 (or whichever method is passed as task) to be invoked iterations times.
Can someone help me understand what's up and down here? Thanks!
awaitdoesn't invoke, it awaits the task representing an already running asynchronous operation to complete, without blocking the threadPrinting!it's becausePrint()is only called once. It never runs asynchronously since it doesn't have anyawaitcalls or anyTask.Run()etc. It returns an already completed task that's awaited three times byPrintLoop, essentially doing nothingPrintLoopthen? One that doesn't simplyawaitan already running task but actually invokes and awaits #iterations"instances" of the task provided as a parameter?Action<Task>rather than aTaskso that you can invoke it asynchronously.Func<Task>.Action<Task>is a method that accepts aTaskas a parameter and returnsvoid.