Search code examples
c#.netwpfxamlpuppeteer-sharp

Software freeze after Puppeteer launch


I have created a small application which should get some data from internet trought Puppeteer Sharp, the problem's that after I instantiate the browser the software freeze without no error.

public partial class MainWindow : Window
{
    public Handler Handler { get; } = new Handler();

    public MainWindow()
    {
        InitializeComponent();            
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Handler.Init(Handler).Wait();
    }
}

as you can see I have Handler which contains all the properties of the software:

public class Handler
{
    private static Url URL = new Url("https://www.diretta.it/");
    public static Browser Browser { get; set; }

    public async Task<bool> Init(Handler prop)
    {
        DotNetEnv.Env.Load("./config.env");

        // The problem's here
        Browser = await Puppeteer.LaunchAsync(new LaunchOptions
        {
            Headless = true,
            ExecutablePath = Environment.GetEnvironmentVariable("CHROME_PATH"),
        });

        return true;
    }
}

where CHROME_PATH is this: CHROME_PATH="C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"

what I did wrong? I have the latest version of Chrome and PuppeteerSharp too.


Solution

  • Change your Window_Loaded event method to async and do an await on the Init method, Event Handler methods are an exception. using async void instead of async Task is ok in this scenario. - Reference (Should I avoid 'async void' event handlers?):

    private async void Window_Loaded(object sender, RoutedEventArgs e) 
    {  
       await Handler.Init(Handler);
    }