BrowserFetcher 使用 await 退出应用程序

我正在使用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();

        }

    }


喵喵时光机
浏览 307回答 1
1回答

MMTTMM

您的 main 方法不会等待异步调用的结果。main 方法退出,关闭应用程序。要修复它,您需要等待异步方法完成。如果您使用的是C# 7.1或更高版本,则可以使用 async Main:public class Program{&nbsp; &nbsp; public static async void Main()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; await TestAsync();&nbsp; &nbsp; }&nbsp; &nbsp; private static async Task TestAsync()&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; await Task.Delay(5000);&nbsp; &nbsp; }}否则你需要同步等待:public class Program{&nbsp; &nbsp; public static void Main()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; TestAsync().GetAwaiter().GetResult();&nbsp; &nbsp; }&nbsp; &nbsp; private static async Task TestAsync()&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; await Task.Delay(5000);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP