Arturo
Arturo

Reputation: 327

Async in loop wait for completion before going on

I have the following code. At first, I thought that this would run an asynctask in each iteration of the foreach loop. However, it's not working like that at all. getPageNumber() is being executed as many times as the foreach dictates but it's being executed all at once, it's not waiting for the completion of an iteration. I want it to wait until one iteration is completed to start another asynctask and not run them all at once. How should I code this? Maybe I should just implement this using another approach... Thank you very much.

string [] lang = {"all", "spanish"};

for (int i = 0; i < 1; i++) {
    foreach (KeyValuePair<string, int> entry in urlsDictionary)
    {
        var pageNumber = getPageNumber("http://" + entry.Value +     
            "&supportedlang=" + lang[i] + "&page=1");
        pageNumber.ContinueWith((t) =>
        {
            int totalPagesR = pageNumber.Result;
            Console.WriteLine("Total pages found " + entry.Key + " : " +
                totalPagesR.ToString());

            var task = DoNavigationAsync("http://" + entry.Value + "&supportedlang" + lang[i] + 
                "&page=", totalPagesR, "<a class=\"search.*?href=\"/app/(.*?)/.*?<span class=\"title\">(.*?)</span>", "folder/name" + entry.Key + lang[i]);
            task.ContinueWith((t2) =>
            {
                Console.WriteLine(entry.Key + " completed...");
            }, TaskScheduler.FromCurrentSynchronizationContext());

        }, TaskScheduler.FromCurrentSynchronizationContext());                   
    }
}

Upvotes: 1

Views: 472

Answers (1)

Servy
Servy

Reputation: 203834

Rather than explicitly adding the continuations, which you could technically use to do what you want (through the use of a state machine that "remembers" where you are in the iteration between continuations) it's much easier to leverage await to handle the continuations for you:

string[] languages = { "all", "spanish" };

foreach (var language in languages)
{
    foreach (var entry in urlsDictionary)
    {
        var pageNumber = await getPageNumber("http://" + entry.Value +
            "&supportedlang=" + language + "&page=1");
        Console.WriteLine("Total pages found " + entry.Key + " : " + pageNumber);

        await DoNavigationAsync("http://" + entry.Value +
            "&supportedlang" + language + "&page=",
            pageNumber,
            "<a class=\"search.*?href=\"/app/(.*?)/.*?<span class=\"title\">(.*?)</span>",
            "folder/name" + entry.Key + language);

        Console.WriteLine(entry.Key + " completed...");
    }
}

Upvotes: 3

Related Questions