Async in loop等待完成后再继续

时间:2015-09-04 20:09:56

标签: c# .net visual-studio loops asynchronous

我有以下代码。起初,我认为这将在foreach循环的每次迭代中运行asynctask。但是,它根本不像那样工作。 getPageNumber()正在按照foreach的指示执行多次,但它一次执行,它不等待迭代的完成。我希望它等到一次迭代完成后再启动另一个asynctask而不是一次全部运行它们。我该怎么编码呢?也许我应该用另一种方法来实现这一点......非常感谢你。

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());                   
    }
}

1 个答案:

答案 0 :(得分:3)

而不是显式添加延迟,你可以技术上使用它来做你想要的(通过使用“记住”你在延续之间的迭代中的状态机)它是< em>很多更容易利用await来处理延期:

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...");
    }
}