使用await

时间:2018-07-26 12:24:03

标签: c# asynchronous puppeteer-sharp

我正在使用Puppeteer-Sharp下载站点的html,我创建了一个名为GetHtml的方法,该方法返回包含站点内容的字符串。问题是,当我拨打await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);

行时

应用程序退出没有任何错误,这是我的代码:

public class Program
{
    public static void Main(string[] args)
    {
        try
        {
            new FixtureController().AddUpdateFixtures();
        }
        catch (Exception ex)
        {
            new Logger().Error(ex);
        }
    }
}

public async Task AddFixtures()
{
    int monthDays = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
    var days = Enumerable.Range(1, monthDays).Select(x => x.ToString("D2")).ToArray();

    HtmlDocument doc = new HtmlDocument(); //this is part of Htmlagilitypack library

    foreach (var day in days)
    {
        //Generate url for this iteration
        Uri url = new Uri("somesite/" + day);

        var html = await NetworkHelper.GetHtml(url);
        doc.LoadHtml(html);
    }
}

因此,每个foreach迭代都会生成一个下载数据的url,方法GetHtml应该返回html,但是到达var html = ..时应用程序退出(没有错误),这是GetHtml的代码:

    public static async Task<string> GetHtml(Uri url)
    {
        try
        { 
            //here the crash
            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        }
        catch (Exception e)
        {
             //No breakpoint point firing
        }

        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);

        var browser = await Puppeteer.LaunchAsync(new LaunchOptions
        {
            Headless = true
        });

        using (Page page = await browser.NewPageAsync())
        {
            await page.GoToAsync(url.ToString());
            return await page.GetContentAsync();
        }
    }

1 个答案:

答案 0 :(得分:2)

您的main方法不等待异步调用的结果。主方法退出,关闭应用程序。要修复它,您需要等待异步方法完成。

如果您使用的是 C#7.1 或更高版本,则可以使用异步Main:

public class Program
{
    public static async void Main()
    {
        await TestAsync();
    }

    private static async Task TestAsync() 
    {
        await Task.Delay(5000);
    }
}

否则,您需要同步等待:

public class Program
{
    public static void Main()
    {
        TestAsync().GetAwaiter().GetResult();
    }

    private static async Task TestAsync() 
    {
        await Task.Delay(5000);
    }
}