await for in csharp

To use the await keyword with a for loop in C#, you need to have an async method which contains the for loop. Inside the loop, you await on a Task or a method that returns a Task. Here's an example:

main.cs
public async Task MyMethodAsync()
{
    for (int i = 0; i < 10; i++)
    {
        // Do some work asynchronously
        await Task.Delay(1000);
        
        // Do some more work after the previous task has completed
        await Task.Run(() => Console.WriteLine($"Iteration {i} completed."));
    }
}
308 chars
12 lines

In the example above, MyMethodAsync is an async method that contains a for loop. Inside the loop, we first use Task.Delay to simulate some async work (this will pause the execution of the loop for one second), and then we use Task.Run to run some work on a background thread.

Both the Task.Delay and Task.Run methods return a Task, which we can await on. By using await, we are pausing the current method's execution until the awaited task has completed. This allows the method to be asynchronous, and avoids blocking the UI thread (if you're writing a GUI application) or any other thread (if you're writing a console or server application).

gistlibby LogSnag