I'm using Puppeteer-Sharp
to download the html
of a site, I created a method called GetHtml
which return a string that contains the site content. The problem is that when I call the line await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
The application exit without any errors, this is my code:
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);
}
}
so each foreach iteration will generate an url which download the data, and the method GetHtml
should return the html
but the application exit (without errors) when reach var html = ..
, this is the code of 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();
}
}
Your main method does not wait for the result of your async call. The main method exits, closing the application. To fix it you need to wait for the async method to finish.
If you're using C# 7.1 or newer you can use async Main:
public class Program
{
public static async void Main()
{
await TestAsync();
}
private static async Task TestAsync()
{
await Task.Delay(5000);
}
}
Otherwise you need to wait synchronously:
public class Program
{
public static void Main()
{
TestAsync().GetAwaiter().GetResult();
}
private static async Task TestAsync()
{
await Task.Delay(5000);
}
}