Janilson
Janilson

Reputation: 1183

How do async methods work when awaiting something in a loop?

Imagine I have an async function that takes data from an url and outputs it to a file, and an async function that calls the first function for a list of urls, like this:

static async Task UrlToFileAsync(Uri url, string filePath)
{
    //...
}

public static async Task GetDataAsync(List<Uri> urlList, string filePath)
{
    foreach (Uri url in urlList)
    {
        await UrlToFileAsync(url, filePath);
    }
}

My question is, will the Task from GetDataAsync only be considered completed when the Task for each url called in the loop is completed? Does the program creates an array or list of Tasks somewhere to monitor the state of each call of UrlToFileAsync?

Upvotes: 2

Views: 162

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38757

Will the Task from GetDataAsync only be considered completed when the Task for each url called in the loop is completed?

Yes, that's correct.

Does the program creates an array or list of Tasks somewhere to monitor the state of each call of UrlToFileAsync?

You're awaiting UrlToFileAsync(), so when the method completes, execution will be returned to GetDataAsync(). async/await basically lets your application release the thread its using back to the thread pool when it does I/O work, and once the I/O work is complete, it will resume the CPU-bound execution and eventually return to the context of the calling method. There's a much more detailed explanation of that here. You can also find more information on Stephen Cleary's blog.

At the moment, you're running each url sequentially, so you're not using the full benefit of asyinc/await. If you want to parallelize the tasks, you should do something like this:

public static async Task GetDataAsync(List<Uri> urlList, string filePath)
{
    // create an array of tasks
    var tasks = urlList.Select(u => UrlToFileAsync(u, filePath)).ToArray();
    // wait for them all to complete
    await Task.WhenAll(tasks);
}

Upvotes: 4

Related Questions