0

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

1 回答 1

3

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

如果您使用的是C# 7.1或更新版本,则可以使用 async 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);
    }
}
于 2018-07-26T12:31:51.070 回答