Home > Net >  Struggling to .Dispose() using return method with PuppeteerSharp
Struggling to .Dispose() using return method with PuppeteerSharp

Time:12-14

I'm struggling to .Dispose() and Chromium is building up and crashing my computer because this is a process that is left on for days.

However, I cannot put .Dispose() after return because it'll be unreachable, and if I put it before return, the content string will become stale.

    var docBContent = await renderHtmlAsync(url2);
    fromDoc.LoadHtml(docBContent);

public static async Task<string> renderHtmlAsync(string url2)
{
    await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
    Browser browser = await Puppeteer.LaunchAsync(new LaunchOptions
    {
        Headless = true
    });
    var page = await browser.NewPageAsync();
    page.DefaultTimeout = 0;
    var navigation = new NavigationOptions
    {
        Timeout = 0,
        WaitUntil = new[] {
                WaitUntilNavigation.DOMContentLoaded }
    };
    await page.GoToAsync(url2, navigation);
    var content = page.GetContentAsync();

    return await content;
}

This is what appears, including with the solutions mentioned so far: enter image description here

How do I tackle this?

CodePudding user response:

You could use a using block for that:

public static async Task<string> renderHtmlAsync(string url2)
{
    await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
    using (Browser browser = await Puppeteer.LaunchAsync(new LaunchOptions
    {
        Headless = true
    }))
    {
        var page = await browser.NewPageAsync();
        page.DefaultTimeout = 0;
        var navigation = new NavigationOptions
        {
            Timeout = 0,
            WaitUntil = new[] {
                    WaitUntilNavigation.DOMContentLoaded }
        };
        await page.GoToAsync(url2, navigation);
        var content = page.GetContentAsync();

        return await content;
    }
}

This works like:

var myObject = new DispoableObject();
try
{
    // insert code
    return result;
}
finally
{
    myObject.Dispose();
}

The code in the finally is always executed, even when an exception is thrown inside the try block.

  • Related